Search code examples
javalambdajava-8remove-if

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


Solution

  • 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);
    }