Java 8 Convert map <String, String []> to map <String, String>

UPDATE (after a question marked as duplicate): A duplicate question / answer does not help me solve my problem, because the card I receive is from an external source.

I am trying to use something using Java functions streamand collect.

I have a map Map<String, String[]>that I need to convert to in Map<String, String>order to collect the first element of the array Stringif it is not empty or does not fit nullif it nullorempty

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 check 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 to do this with an empty array or null value for my source 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'm doing wrong here?

+4

All Articles