lambdas in removeIf

1.1k views Asked by At
HashSet<Integer> liczby = new HashSet<Integer>();
liczby.add(1);
liczby.add(2); 
liczby.add(3);
liczby.add(4);
liczby.removeIf ((Integer any) -> { return liczby.contains(3); });

for(Iterator<Integer> it = liczby.iterator(); it.hasNext();){
    Integer l2 = it.next();
    System.out.println(l2);
}

I can't understand why removeIf deletes not only 3 but also 1 and 2 condition should be satisfied only by 3...

2

There are 2 answers

2
azro On BEST ANSWER

The lambda is applied on each element and check if 3 is present, if yes it will delete the element :

1 -> 3 is present -> delete 1
2 -> 3 is present -> delete 2
3 -> 3 is present -> delete 3
4 -> 3 is not present -> don't delete 4

To remove all 3 element, you can use one of those solutions :

liczby.removeIf(any -> any.equals(3));
//-------------------------------------------------
liczby.removeIf(new Integer(3)::equals);
//-------------------------------------------------
Integer toRemove = 3;
liczby.removeIf(toRemove::equals);


TIPS

Your lambda can be simplified as :

liczby.removeIf(any -> liczby.contains(3));

For-each loop might be easier to use for simple iteration :

for(Integer i : liczby){
    System.out.println(i);
}
1
Ousmane D. On

Think of it this way... as long as the set contains 3 it will keep removing hence the current outcome.

If you want to remove the 3 only then do this:

liczby.removeIf(e -> e == 3);