Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambdas in removeIf

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...

like image 267
QWERTY1234567890 Avatar asked Aug 09 '26 18:08

QWERTY1234567890


2 Answers

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);
like image 191
Ousmane D. Avatar answered Aug 12 '26 15:08

Ousmane D.


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);
}
like image 36
azro Avatar answered Aug 12 '26 14:08

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!