I am dealing with a Map<String,String>
that has null
entries in the key and/or value:
Map<String, String> headers = new HashMap<>();
headers.put("SomE", "GreETing");
headers.put("HELLO", null);
headers.put(null, "WOrLd");
headers.keySet().stream().forEach(k -> System.out.println(k + " => " + copy.get(k)));
I get the following output:
SomE => GreETing
HELLO => null
null => WOrLd
I need to transform the map, so all the non-null values are converted to lowercase, like so:
some => greeting
hello => null
null => world
I am trying to use Java 8 streams API, but the following code is throwing NullPointerException
:
Map<String,String> copy
= headers.entrySet()
.stream()
.collect(
Collectors.toMap(
it -> it.getKey() != null ? it.getKey().toLowerCase() : null,
it -> it.getValue() != null ? it.getValue().toLowerCase() : null));
copy.keySet().stream().forEach(k -> System.out.println(k + " => " + copy.get(k)));
If I comment out the last two map entries, the program executes, so there must be an issue with how Collectors.toMap
works when keys or values are null. How do I use the streams API to work around this?
key
can be null.value
can't be null