Home > Net >  Why does removing items from an arraylist that fullfill one of the two conditions not work?
Why does removing items from an arraylist that fullfill one of the two conditions not work?

Time:07-12

Ok so I have an integer ArrayList from which I want to remove the entries that are either odd or are bigger than 100. My code, however, does not work and I do not really get why?

list.add(1);
        list.add(899);
        list.add(5);
        list.add(647);
        list.add(4);
        list.add(804);
        list.add(103);
        ArrayList<Integer> list2  = removeEntries(list);

public static ArrayList<Integer> removeEntries(ArrayList<Integer> list1) {
        for(int i = 0; i < list1.size(); i  ) {
            while(list1.get(i) % 2 != 0 || list1.get(i) > 100) {
                if(i != list1.size()) list1.remove(i);
            }
        }
        return list1;
    }

This does not give me the right list2-entries but I do not understand as to why...

CodePudding user response:

List#removeIf

Use the Collection#removeIf method, inherited by List. Pass a Predicate with your criteria for removal.

Like this:

list.removeIf(x -> x != null && (x % 2 == 1 || x > 100));
System.out.println(list);  // [4]

CodePudding user response:

The while loop in your method is incorrect, this should be an if:

List<Integer> filteredList = new ArrayList<>();
for (Integer i : list1) {
    if (i % 2 == 0 && i < 100) {
        filteredList.add(i);
    }
}
return filteredList;

Pretty sure using remove() while you're iterating through a collection will throw a ConcurrentModificationException.

  • Related