I am going over some Java 8 code and observed something like below, can someone please help me understand what it actually means?
hashSetA.removeif(hasSetB::remove);
I am going over some Java 8 code and observed something like below, can someone please help me understand what it actually means?
hashSetA.removeif(hasSetB::remove);
A method reference is a shorthand for passing the argument of the lambda to the method. In other words, this snippet:
hashSetA.removeIf(hashSetB::remove);
Is equivalent to:
hashSetA.removeIf(itemFromA -> hashSetB.remove(itemFromA));
remove
returns true if an item was actually remove. So what's actually going on here is that removeIf
goes over all the items in hashSetA
, and attempts to remove each one from hashSetB
. If the item actually was in hashSetB
, it's removed from it, and then removed from hashSetA
.