简体   繁体   English

Java 8:使用流检查两个列表中的公共元素

[英]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重写equalshashCode方法。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM