How to convert map <Shape, int []> to Map <Shape, Set <Integer>> in Java 8?
2 answers
I edited the question in the hope that Set<Integer>- this is what you really need, because you cannot have a primitive Settype Set<int>.
map.entrySet()
.stream()
.collect(Collectors.toMap(
Entry::getKey,
x -> Arrays.stream(x.getValue()).boxed().collect(Collectors.toSet())
));
On the other hand, if you really want a unique primitives, then they will work distinctand toArray, but will still type Map<Shape, int[]>:
map.entrySet()
.stream()
.collect(Collectors.toMap(
Entry::getKey,
x -> Arrays.stream(x.getValue()).distinct().toArray()
));
+5
The following is a method to convert an array intto Set<Integer>:
private Set<Integer> convertArrayToSet(int[] array) {
return stream(array).boxed().collect(toSet());
}
You need to skip each map value using this method:
public Map<Shape, Set<Integer>> convert(Map<Shape, int[]> map) {
return map.entrySet()
.stream()
.collect(toMap(e -> e.getKey(), e -> convertArrayToSet(e.getValue())));
}
Arrays, Collectors, .
+3