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
3 Answers 3
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
Ashvin Sharma
The question explicitly mentions Java 8 so Java 9 is out of the scope of this question
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
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
lang-java
Map.of
exists.