简体   繁体   中英

Intersection of list of lists java

I am trying to find the intersection of two list of lists in 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]]

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. Hence the sublist [4,5,6] in list1 gets separated into [4,5] and [6] after the intersection.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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