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

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

问题描述

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

重复发生时,我得到重复的密钥异常。

I get duplicate key exception when duplicates occurs.

当重复出现时,是否可以忽略将值添加到地图中?

Is it possible to ignore to add the values to map when the duplicates occurs?

当存在重复时它应该继续忽略那个重复的密钥。

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

推荐答案

这可以使用 mergeFunction 参数 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天全站免登陆