Java – delete items from the list or add build new list?

Usually, I have to iterate over an ArrayList and want to create a subset from it based on any condition

From a performance perspective: use iterator and iterator for the elements I want to delete Is remove () better, or should I add these elements to the new list?

for (Iterator<Object> it = list.iterator(); it.hasNext(); ) {
    Object item = it.next();
    if (!conditionMatches(item)) {
        it.remove();
    }
}

or

List<Object> newList = new ArrayList<>();
for (Object item : list) {
   it (contitionMatches(item)) {
      newList.add(item);
   }
}

Solution

Option 1 does not apply to read-only lists, such as arrays The list returned by aslist

In addition, when the list is long, deleting from the ArrayList is a big cost, because most of the backup arrays must be copied

Option 2 applies to all lists

This is also the pattern we encourage to use with streams:

List<String> l = Arrays.asList("A","B","C");
    List<String> filtered = l.stream()
            .filter(s -> s.equals("A"))
            .collect(Collectors.toList());

With all due respect – use this one The savings in option 1 are illusory

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>