1

I am writing a function to convert array to Map using Java 8 Stream.

    public static <K, V> Map<K, V> toMap(Object... entries) {
    // Requirements:
    // entries must be K1, V1, K2, V2, .... ( even length )
    if (entries.length % 2 == 1) {
        throw new IllegalArgumentException("Invalid entries");
    }

    // TODO
    Arrays.stream(entries).????
}

Valid usages

    Map<String, Integer> map1 = toMap("k1", 1, "k2", 2);

    Map<String, String> map2 = toMap("k1", "v1", "k2", "v2", "k3", "v3");

Invalid usages

    Map<String, Integer> map1 = toMap("k1", 1, "k2", 2, "k3");

Any helps?

Thanks!

1
  • 1
    What is your purpose for this? Map.of exists. Commented Jul 29, 2019 at 5:07

3 Answers 3

4

Did you realize it already exists? It's been around since Java 9.

The following creates an immutable map of the keys and values.

 Map<String, String> map2 = Map.of("k1", "v1", "k2", "v2", "k3", "v3");

For a mutable map do

 Map<String, String> map2 = new HashMap<>(Map.of("k1", "v1", "k2", "v2", "k3", "v3"));
Sign up to request clarification or add additional context in comments.

1 Comment

The question explicitly mentions Java 8 so Java 9 is out of the scope of this question
3

You may use

    public static <K, V> Map<K, V> toMap(
                               Class<K> keyType, Class<V> valueType, Object... entries) {
    if(entries.length % 2 == 1)
        throw new IllegalArgumentException("Invalid entries");
    return IntStream.range(0, entries.length/2).map(i -> i*2)
        .collect(HashMap::new,
                 (m,i)->m.put(keyType.cast(entries[i]), valueType.cast(entries[i+1])),
                 Map::putAll);
}

Comments

0

You can use it this way

Map map = ArrayUtils.toMap(arrayName);

And you can import ArrayUtils from :

import org.apache.commons.lang3.ArrayUtils;

Just include Apache JARs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.