Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inverting Map<Integer, Integer> into a Map<key, list<Integer>> using Streams

Is it possible to convert a Java Map<Integer, Integer> m0 to a new Map<Integer, List<Integer>> m1
where in the m1 map to have key as value of m0 map and value as List<Integer> of keys of m0 map?

In other words, this task it is about the inverting key-value pairs grouped by values.

I have tried the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 public static void main(String[] args) {
        Map<Integer, Integer> m = new HashMap<>();
        m.put(1, 1);
        m.put(2, 1);
        m.put(3, 1);
        m.put(4, 2);
        m.put(5, 2);
        m.put(6, 2);
        m.put(7, 2);

        Map<Integer, List<Integer>> personByAge 
                = m.values()
                .stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.toList()));

        Iterator it = personByAge.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, List<Integer>> me = (Map.Entry)it.next();
            System.out.println(me.getKey() + " <- key" );
            for (int i : me.getValue())
            {
                System.out.println("Values: " + i);
            }
        }
    }

But the values in the second map are wrong.

The values should be:

1 <- key Values: 1 Values: 2 Values: 3
2 <- key Values: 4 Values: 5 Values: 6 Values: 7

But I’m getting:

1 <- key Values: 1 Values: 1 Values: 1
2 <- key Values: 2 Values: 2 Values: 2 Values: 2

>Solution :

it is about the inverting key values pair grouped by values

If you want to invert the Map as you’ve said in the comments, you need to create a stream over the entries of the source map, not over the values:

Map<Integer, List<Integer>> personByAge = m.entrySet()
    .stream()
    .collect(Collectors.groupingBy(
        Map.Entry::getValue,
        Collectors.mapping(Map.Entry::getKey,
            Collectors.toList())));
        
personByAge.forEach((k, v) -> System.out.println(k + " -> " + v));

Output:

1 -> [1, 2, 3]
2 -> [4, 5, 6, 7]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading