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

Question

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

Answers 2
Added at 2017-11-30 16:11
Tags
Question

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

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

Any ideas?

Answers to

How to convert Map&lt;Shape, int[]&gt; to Map&lt;Shape, Set&lt;Integer&gt;&gt; in Java 8?

nr: #1 dodano: 2017-11-30 16:11

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()

    ));
nr: #2 dodano: 2017-11-30 16:11

Here is a method to transform an int array to a Set<Integer>:

private Set<Integer> convertArrayToSet(int[] array) {
    return stream(array).boxed().collect(toSet());
}

You need to skip each value of the map through 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())));
}

I used static imports of Arrays, Collectors to make the snippets shorter.

Source Show
◀ Wstecz