2

I have 2 arrays (same size) String[] and Object[]. The question: is there a more elegant way to convert them to Map than this?

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

Java 8 style maybe?

Important notes:

  • values may contain null value
  • keys contains non-null unique elements
1
  • make sure that the sizes are equal, otherwise you might get a ArrayIndexOutOfBoundsException Commented Dec 28, 2017 at 16:08

1 Answer 1

1

To solve this, you can use the following code:

public class Test {
    static String[] keys = {"String1", "String2"};
    static Object[] values = {new Object(), new Object()};

    public static void main(String[] args) {
        Map<String, Object> map = IntStream.range(0, keys.length)
                .boxed()
                .collect(Collectors.toMap(i -> keys[i], i -> values[i]));
    }
}

As can you see first I have created a range from zero to keys.length, then we have replaced the primitive values of the stream with their corresponding object wrapper classes. At the end we used Collectors.toMap method to actually create the map. Also make sure that the sizes to be equal.

Sign up to request clarification or add additional context in comments.

22 Comments

There is a problem. That fails with NPE if one of values is null.
This was happening because the array were not initialized. It was an example but please see my updated answer.
Map itself supports null values but overridden merge() method from HashMap does not. @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null) throw new NullPointerException();
@AlexMamo you example can be extended with "dirty hack" :) Following code will work because Hashtable's merge() implementation accepts null 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)); Map<String, Object> result = new HashMap<>(map);
@NikolayShevchenko right, I should have made myself more clear. what I meant is that you can build a custom collector and provide the merge function as you want (if one is needed)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.