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!

asked Jul 29, 2019 at 4:14
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"));
answered Jul 29, 2019 at 4:19

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);
}
answered Jul 29, 2019 at 4:15

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

answered Jul 29, 2019 at 9:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.