Search code examples
javajava-stream

How to get indexes of all duplicate elements by using the Java stream API


How can I get the indexes of all duplicate elements by using the Java stream API?

For example, we have:

List<Integer> input =
        new ArrayList<>(Arrays.asList(312, 312, 195, 195, 195, 851, 335, 851, 99));

I could group same elements like this:

result = input.stream().collect(Collectors.groupingBy(input::indexOf))
//result = {0=[312, 312], 2=[195, 195, 195], 5=[851, 851], 6=[335], 8=[99]}

But I want get a result like this:

{312=[0, 1], 195=[2, 3, 4], 851=[5, 7]}

or just like this:

(0,1,2,3,4,5,7)

How can I do this?


Solution

  • You can Use IntStream

    Map<Integer, List<Integer>> map = IntStream.range(0, input.size())
                    .boxed()
                    .collect(Collectors.groupingBy(i -> input.get(i), HashMap::new,
                            Collectors.toCollection(ArrayList::new)));
    
    // output : {99=[8], 851=[5, 7], 195=[2, 3, 4], 312=[0, 1], 335=[6]}
    

    Once you have all the values and their indexes you can simply filter out the entries which have more than 1 value.
    Full example:

    Map<Integer, List<Integer>> map = IntStream.range(0, input.size())
                    .boxed()
                    .collect(Collectors.groupingBy(i -> input.get(i), HashMap::new,
                            Collectors.toCollection(ArrayList::new)))
                    .entrySet()
                    .stream()
                    .filter(e -> e.getValue().size()>1)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));