Java 8 使用方法引用的 removeIf 方法

huangapple go评论76阅读模式
英文:

Java 8 removeif with method reference

问题

我正在查阅一些 Java 8 的代码,并观察到类似以下的内容,有人可以帮我理解它实际上是什么意思吗?

hashSetA.removeif(hashSetB::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);

答案1

得分: 1

方法引用是传递 lambda 参数到方法的简写方式。换句话说,下面这段代码:

hashSetA.removeIf(hashSetB::remove);

等同于:

hashSetA.removeIf(itemFromA -> hashSetB.remove(itemFromA));

remove 方法在实际移除项时返回 true。因此,这里的实际操作是 removeIf 遍历 hashSetA 中的所有项,并尝试从 hashSetB 中移除每一项。如果该项实际上在 hashSetB 中,它会被从中移除,然后从 hashSetA 中移除。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月12日 22:02:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63861115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定