您当前的位置: 首页 > 

qq_34412985

暂无认证

  • 0浏览

    0关注

    1061博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

List转成一个Map

qq_34412985 发布时间:2019-05-15 18:20:29 ,浏览量:0

Map merged = lists.stream()
        .map(Map::entrySet)
        .flatMap(Set::stream)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

 

// 不想覆盖,保留最初的值: 
lists.stream().flatMap(m -> m.entrySet().stream())
              .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a));
              
// 覆盖key相同的值,
lists.stream().flatMap(m -> m.entrySet().stream())
              .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b)); 

一种更简单的方式用StreamEx,一个第三方开源库:

// 没有MergeFunction,如果在不同的Map有相同的Key会报错:
StreamEx.of(lists).flatMapToEntry(Function.identity()).toMap();

// 保留最初的值
StreamEx.of(lists).flatMapToEntry(Function.identity()).toMap((a, b) -> a);

// 覆盖最初的值,用最后的值
StreamEx.of(lists).flatMapToEntry(Function.identity()).toMap((a, b) -> b);

1, 对的,如果Map里有Null值会出错的,更多的原因可以参阅:java-8-nullpointerexception-in-collectors-tomap。 你可以把Null值filter掉,或者用forEach + putAll,如果Null值是你需要保留的:

lists.stream().flatMap(m -> m.entrySet().stream()).filter(e -> e.getValue() != null)...

//或者:
StreamEx.of(lists).flatMapToEntry(Function.identity()).nonNullValues()...

 

 

 

 

关注
打赏
1653291990
查看更多评论
立即登录/注册

微信扫码登录

0.0424s