Converting Array to HashMap using Java 8 Stream

Shivani Pundir :

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!

Kapil Kumar Shishodia :

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);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311426&siteId=1