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:
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]