繁体   English   中英

使用java stream比较两个字符串列表

[英]Compare two lists of string using java stream

我有两个列表A和B.两个都有数百万个元素。 我想比较并获取列表A中但不在列表B中的所有元素。以下是获取元素的低效方法。

   if (!B.containsAll(A)) {
        for (Integer id : A) {
            if (!B.contains(id)) {
                System.out.println(id);
            }
        }
    }

我寻找一种有效的方式,有或没有流来获取元素

在这方面的帮助表示赞赏。

谢谢

你不需要比较

List<Integer> c = new ArrayList<>(a);
c.removeAll(b);

如果您不介意丢失原始列表数据

a.removeAll(b);

这样的事情应该足够了:

Set<Integer> container = new HashSet<>(ListB);
ListA.stream()
     .filter(id -> !container.contains(id))
     .forEach(System.out::println);

或非流:

Set<Integer> container = new HashSet<>(ListB);
for(Integer id : ListA)
    if(!container.contains(id));
       System.out.println(id);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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