英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论