使用 Java 8 Stream 将 Array 转换为 HashMap

我正在编写一个使用 Java 8 Stream 将数组转换为 Map 的函数。


    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).????

}

有效用法


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


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

无效用法


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

有帮助吗?


慕神8447489
浏览 113回答 3
3回答

收到一只叮咚

你意识到它已经存在了吗?从那以后就存在了Java 9。以下创建键和值的不可变映射。&nbsp;Map<String,&nbsp;String>&nbsp;map2&nbsp;=&nbsp;Map.of("k1",&nbsp;"v1",&nbsp;"k2",&nbsp;"v2",&nbsp;"k3",&nbsp;"v3");对于可变地图做&nbsp;Map<String,&nbsp;String>&nbsp;map2&nbsp;=&nbsp;new&nbsp;HashMap<>(Map.of("k1",&nbsp;"v1",&nbsp;"k2",&nbsp;"v2",&nbsp;"k3",&nbsp;"v3"));

喵喵时光机

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

慕后森

你可以这样使用Map&nbsp;map&nbsp;=&nbsp;ArrayUtils.toMap(arrayName);您可以从以下位置导入 ArrayUtils:import&nbsp;org.apache.commons.lang3.ArrayUtils;只包含 Apache JAR
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java