[英]Intersection of list of lists java
I am trying to find the intersection of two list of lists in Java. 我试图在Java中找到两个列表的交集。
For instance, 例如,
list1 = [[1][2][3][7][4,5,6][8,9][10]]
list2 = [[1][2][3,7,8][4,5,10][6,9]]
Intersection of two lists has to be [[1][2][3][7][4,5][6][8][9][10]]
两个列表的交点必须为[[1][2][3][7][4,5][6][8][9][10]]
This is because if we scan the fourth element in list1 , it is [4,5,6] , whereas in list2, we have[4,5] in a list and [6] in a separate sublist. 这是因为,如果我们扫描list1中的第四个元素,它是[4,5,6],而在list2中,我们在列表中有[4,5],在单独的子列表中有[6]。 Hence the sublist [4,5,6]
in list1 gets separated into [4,5] and [6] after the intersection. 因此,列表1中的子列表[4,5,6]
在交集后被分成[4,5]和[6]。
Any help is appreciated !! 任何帮助表示赞赏!
A streams way of doing it: 一种流的方法:
List<List<Integer>> l1
= Arrays.asList(
Arrays.asList(1),
Arrays.asList(2),
Arrays.asList(3),
Arrays.asList(7),
Arrays.asList(4, 5, 6),
Arrays.asList(8, 9),
Arrays.asList(10));
List<List<Integer>> l2
= Arrays.asList(
Arrays.asList(1),
Arrays.asList(2),
Arrays.asList(3, 7, 8),
Arrays.asList(4, 5, 10),
Arrays.asList(6, 9));
List<List<Integer>> intersect
= l1.stream()
.flatMap(sl1 -> l2.stream().map(sl2 -> {
List<Integer> lout = new ArrayList<>();
lout.addAll(sl1);
lout.retainAll(sl2);
return lout;
}))
.filter(l -> l.size() > 0)
.distinct()
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.