使用流生成地图时忽略重复项 [英] Ignore duplicates when producing map using streams

查看:30
本文介绍了使用流生成地图时忽略重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Map<String, String> phoneBook = people.stream()
                                      .collect(toMap(Person::getName,
                                                     Person::getAddress));

当发现重复元素时,我得到 java.lang.IllegalStateException: Duplicate key.

I get java.lang.IllegalStateException: Duplicate key when a duplicated element is found.

是否可以在向地图添加值时忽略此类异常?

Is it possible to ignore such exception on adding values to the map?

当有重复时,它应该继续忽略该重复键.

When there is duplicate it simply should continue by ignoring that duplicate key.

推荐答案

这可以使用 Collectors.toMap(keyMapper, valueMapper, mergeFunction):

This is possible using the mergeFunction parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction):

Map<String, String> phoneBook = 
    people.stream()
          .collect(Collectors.toMap(
             Person::getName,
             Person::getAddress,
             (address1, address2) -> {
                 System.out.println("duplicate key found!");
                 return address1;
             }
          ));

mergeFunction 是对与同一键关联的两个值进行操作的函数.adress1 对应于收集元素时遇到的第一个地址,adress2 对应于遇到的第二个地址:这个 lambda 只是告诉保留第一个地址并忽略第二个.

mergeFunction is a function that operates on two values associated with the same key. adress1 corresponds to the first address that was encountered when collecting elements and adress2 corresponds to the second address encountered: this lambda just tells to keep the first address and ignores the second.

这篇关于使用流生成地图时忽略重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆