Java. 2 arrays to map

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]} ...

public Map<String, Object> arraysToMap(String[] keys, Object[] values) {
    ...
}

2 arrays to Map with the old good for loop

public Map<String, Object> arraysToMap(String[] keys, Object[] values) {
    Map<String, Object> map = new HashMap<>();
    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }
    return map;
}

However, now in 2018 (almost) this is not cool to use for loops

Java 8 style - 2 arrays to Map

public Map<String, Object> arraysToMap(String[] keys, Object[] values) {
    return IntStream.range(0, keys.length).boxed()
        .collect(Collectors.toMap(i -> keys[i], i -> values[i]));
}

There is the issue with that solution - it throws Null Pointer Exception if values contains nulls

Another Java 8 style solution - 2 arrays to Map

public Map<String, Object> arraysToMap(String[] keys, Object[] values) {
    Map<String, Object> map = IntStream.range(0, keys.length).boxed()
        .collect(Collectors.toMap(i -> keys[i], i -> values[i], (v1, v2) -> v1, Hashtable::new)); 
    return new HashMap<>(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

public Map<String, Object> arraysToMap(String[] keys, Object[] values) {
    Map<String, Object> map = new HashMap<>();
    IntStream.range(0, keys.length).boxed().forEach(i -> map.put(keys[i], values[i]));
    return map;
}

In that solution we just replaced a for loop with Java 8 IntStream. But that works


You may also find these posts interesting: