Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Map<Shape, int[]> to Map<Shape, Set<Integer>> in Java 8?

I'm pretty new to Java 8 and I have the following requirement to convert:

Map<Shape, int[]> --> Map<Shape, Set<Integer>>

Any ideas?

like image 556
Shvalb Avatar asked Jan 30 '23 03:01

Shvalb


1 Answers

I've edited the question in hope that a Set<Integer> is what you really need, cause you can't have a primitive Set of type 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 unique primitives, then a distinct and toArray will work, but the type is still going to be Map<Shape, int[]>:

 map.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Entry::getKey,
                    x -> Arrays.stream(x.getValue()).distinct().toArray()

    ));
like image 81
Eugene Avatar answered Jan 31 '23 18:01

Eugene