I have two lists which are also having some duplicate elements , i am converting this list to map as key value pair with element index as the value for the key - element
List 1 : [1, 2, 3, 4, 5, 6, 7, 2] = >
MAP 1 (Map, List>) : {1=[0], 2=[1, 7], 3=[2], 4=[3], 5=[4], 6=[5], 7=[6]}
List 2 : [3, 3, 2, 4, 7]
= > MAP 2 (Map, List>) : {2=[2], 3=[0, 1], 4=[3], 7=[4]}
i am trying to collect matching keys from both of the maps and club it another map
For above two it would give the result : {[2]=[0, 1], [3]=[3], [6]=[4], [1, 7]=[2]}
Post this , i am taking the cartesian product of key , values and only retaining the unique elements
Final output [[0, 2], [1, 2], [3, 3], [4, 6], [2, 1], [2, 7]] . These is the indices of common elements
Below is the code that i have come up with to achieve this , is there any better way i can achieve the same . I feel it will be too much costly at run time for larger lists .
List<List<Integer>> cartesianProduct = new ArrayList<>(); List<String> distinct1 = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "2") List<String> distinct2 = Arrays.asList["3", "3", "2", "4", "7"] Map<String, List<Integer>> result1 = IntStream.range(0, distinct1.size()).boxed() .collect(Collectors.groupingBy(i -> distinct1.get(i))); Map<String, List<Integer>> result2 = IntStream.range(0, distinct2.size()).boxed() .collect(Collectors.groupingBy(i -> distinct2.get(i))); result1.entrySet().stream() .filter(x -> result2.containsKey(x.getKey())) .collect(Collectors.toMap(x -> x.getValue(), x -> result2.get(x.getKey()))) .entrySet().forEach(a1 -> a1.getValue().stream() .forEach(b1 -> a1.getKey().stream().forEach(c1 -> cartesianProduct.add(Arrays.asList(b1, c1))))); List<List<Integer>> listWithoutDuplicates = cartesianProduct.stream() .distinct() .collect(Collectors.toList());