I'm new to Streams and I want something like this:
I have an input Map with <String, List<String>>
. I want to read this map in a stream and assign it to an output map with <String, String>
with the value being the first element of the value list from input map.
Example:
**Input:**
{key1, [value1 value2]}
{key2, null}
**Output**
{key1, value1}
{key2, null}
Notice, when the list in the first map is null, then it should be written as null in the second map. If the list is empty, then it should also write null in the second map value
What I have tried:
Map<String, String> output= input.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(0)));
This gives a java.lang.NullPointerException
when the list is empty in the first map.