UPDATE (after question marked as duplicate): Duplicate question/answer does not help me solve my issue, as the map I am getting is from external source.
I am trying to work something out using Java stream
and collect
features.
I have a map of Map<String, String[]>
which I needs to convert to a Map<String, String>
picking up the first element of the String
array if it's not empty or putting null
if it's null
or empty
private Map<String, String> convertMyMap(Map<String, String[]> originalMap) {
return originalMap.entrySet().stream().collect(
Collectors.toMap(
e -> e.getKey(),
e -> {
if (ArrayUtils.isNotEmpty(e.getValue()))
return e.getValue()[0];
return null;
}
));
I use below code to test it
Map<String, String[]> params = new HashMap<String, String[]>();
params.put("test", new String[]{"1"});
params.put("test1", new String[]{"2", "1"});
//params.put("test2", new String[]{}); // THIS THROWS NPE
//params.put("test3", null); // THIS THROWS NPE
convertMyMap(params).forEach((key, value) -> System.out.println(key + " "+ value));
As you can see when I try this with an empty array or null value for my original map, it throws NPE.
Exception in thread "main" java.lang.NullPointerException
at java.util.HashMap.merge(Unknown Source)
at java.util.stream.Collectors.lambda$toMap$172(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source)
at java.util.HashMap$EntrySpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
Any ideas what I am doing wrong here?