-5

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

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

1

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    HashSet has `removeIf` since java 8 See: https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html from Collection https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html – pL4Gu33 Sep 12 '20 at 14:13