[英]Java 8: check for common elements in two lists using streams
I'm looking for a statment to check if there is any match in two lists of Users, according to Username. 根据用户名,我正在寻找一条语句来检查两个用户列表中是否有匹配项。
List<User> a;
List<User> b;
for (User user : a) {
for (User newUser : b) {
if (user.getName().equals(newUser.getName())) {
}
}
}
How can I write this in java 8? 如何在Java 8中编写此代码? Somthing like this:
像这样的东西:
List<User> intersect = a.stream()
.filter(User::getName)
.collect(Collectors.toList());
When User is correctly defined with a hashCode
and equals
(otherwise you might try TreeSet
instead of HashSet
), do set-operations: 如果使用
hashCode
正确地定义了User并equals
(否则,您可以尝试使用TreeSet
而不是HashSet
),请执行设置操作:
Set<User> common = new HashSet<>(a);
common.retainAll(b);
If User.getName
is not used for equality: 如果
User.getName
不用于相等性:
Set<User> common = new TreeSet<>(Comparator.comparing(User::getName));
common.addAll(a);
common.retainAll(b);
Two nested for loops on lists (also as streams) would have complexity O(N²), whereas this is O(N.log N). 列表上的两个嵌套for循环(也作为流)的复杂度为O(N²),而复杂度为O(N.log N)。
You can do something like below: 您可以执行以下操作:
List<User> intersect = a.stream()
.filter(b::contains)
.collect(Collectors.toList());
You need to override equals
and hashCode
methods in User
. 您需要在
User
重写equals
和hashCode
方法。 For optimization, you can convert b
to HashSet
first. 为了优化,可以先将
b
转换为HashSet
。
One way to do that using Stream.anyMatch
(this would break
within if
) could be : 使用
Stream.anyMatch
做到这一点的一种方法( if
在中会break
)可能是:
a.stream().filter(user -> b.stream().anyMatch(newUser -> user.getName().equals(newUser.getName())))
.map(User::getName)
.forEach(System.out::println); // logic inside 'if' here (print for e.g.)
If you want to repeat the loop( if
logic) for all such matches : 如果要为所有此类匹配重复循环(
if
逻辑):
a.forEach(user -> b.stream()
.filter(newUser -> user.getName().equals(newUser.getName()))
.map(newUser -> user.getName())
.forEach(System.out::println));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.