栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

合并两个地图 使用Java 8 Stream API

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

合并两个地图 使用Java 8 Stream API

@Testpublic void test14() throws Exception {    Map<String, Integer> m1 = ImmutableMap.of("a", 2, "b", 3);    Map<String, Integer> m2 = ImmutableMap.of("a", 3, "c", 4);    Map<String, Integer> mx = Stream.of(m1, m2)        .map(Map::entrySet)          // converts each map into an entry set        .flatMap(Collection::stream) // converts each set into an entry stream, then    // "concatenates" it in place of the original set        .collect( Collectors.toMap(        // collects into a map     Map.Entry::getKey,   // where each entry is based     Map.Entry::getValue, // on the entries in the stream     Integer::max         // such that if a value already exist for    // a given key, the max of the old    // and new value is taken )        )    ;        Map<String, Integer> expected = ImmutableMap.of("a", 3, "b", 3, "c", 4);    assertEquals(expected, mx);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419106.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号