当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Ignore duplicates when producing map using streams

问题描述:

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.

网友答案:

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

网友答案:

As said in JavaDocs:

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

So you should use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead. Just provide merge function, that will determine, which one of duplicates needed to put in map. For example, if you don't care which one, just call

Map<String, String> phoneBook = people.stream()
  .collect(Collectors.toMap(Person::getName, Person::getAddress, (p1, p2) -> p1));
分享给朋友:
您可能感兴趣的文章:
随机阅读: