Let’s assume we have 2 arrays - String[] keys
and Object[] values
.
values
may contain null
elements, keys
contains non-null unique elements.
The goal is to implement the method that creates a Map with key-value pairs {keys[0], values[0]}, {keys[1], values[1]} ...
2 arrays to Map with the old good for
loop
However, now in 2018 (almost) this is not cool to use for
loops
Java 8 style - 2 arrays to Map
There is the issue with that solution - it throws Null Pointer Exception if values
contains null
s
Another Java 8 style solution - 2 arrays to Map
It doesn’t throw NPE but there is another issue. The result doesn’t contain key-value pairs where the value
is null
Hibryd Java 8 style solution - 2 arrays to Map
In that solution we just replaced a for
loop with Java 8 IntStream.
But that works
You may also find these posts interesting: