Convertendo Array para HashMap usando Java 8 Corrente

Shivani Pundir:

Eu estou escrevendo uma função para conjunto convertido ao mapa usando 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).????
}

usos válidos

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

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

usos inválidos

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

Qualquer ajuda?

Obrigado!

Kapil Kumar Shishodia:

Você pode usar

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

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=317696&siteId=1
Recomendado
Clasificación