NimChimpsky NimChimpsky - 6 months ago 8
Java Question

Convert Map<Long, MyObject> to Map<Long, List<MyObject>>

using java8 and the stream api.

There is only one MyObject, and I want to convert

Map<Long, MyObject>


to

Map<Long, List<MyObject>>


where the list has one element ?

Answer
Map<Long, List<MyObject>> newMap = oldMap.entrySet().stream()
                 .collect(Collectors.toMap(
                            Entry::getKey, 
                            e -> new ArrayList<>(Arrays.asList(e.getValue()))));

If immutable list in value is okay, the last line may be simplified a bit:

                            e -> Collections.nCopies(1, e.getValue())));