简体   繁体   English

嵌套列表java 8流之间的交集

[英]Intersection between nested lists java 8 streams

I have a nested list of Long . 我有一个嵌套的Long列表。 for example: 例如:

List<List<Long>> ids = [[1,2,3],[1,2,3,4],[2,3]];

Is there a way using streams to create a new list of items that are present in all the lists: 有没有办法使用流来创建所有列表中存在的新项目列表:

List<Long> result = [2,3];

There is quite concise solution without stream: 没有流的解决方案非常简洁:

List<Long> result = new ArrayList<>(ids.get(0));
ids.forEach(result::retainAll);

System.out.println(result);

Update : as it was mentioned in the comments by @ernest_k to avoid the superfluous retainAll() call you can get sublist before: 更新 :正如@ernest_k在评论中提到的,以避免多余的retainAll()调用,您可以在之前获取子列表:

ids.subList(1, ids.size()).forEach(result::retainAll); 

Here's a (less concise) Stream version using reduce : 这是使用reduce的(不太简洁) Stream版本:

List<Long> intersect = ids.stream()
                          .reduce(ids.get(0),
                                  (l1,l2) -> {
                                      l1.retainAll(l2);
                                      return l1;
                                  });

Or (if we want to avoid mutating the original List s): 或者(如果我们想避免改变原始List ):

List<Long> intersect = ids.stream()
                          .reduce(new ArrayList<>(ids.get(0)),
                                  (l1,l2) -> {
                                      l1.retainAll(l2);
                                      return l1;
                                  });

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

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