Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore duplicates when producing map using streams

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

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.

like image 504
Patan Avatar asked Aug 31 '15 13:08

Patan


People also ask

How do you remove duplicate elements in a stream?

You can use the Stream. distinct() method to remove duplicates from a Stream in Java 8 and beyond. The distinct() method behaves like a distinct clause of SQL, which eliminates duplicate rows from the result set.

Which map does not allow duplicates?

HashMap is an implementation of Map Interface, which maps a key to value. Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys.

Are duplicates allowed in map?

The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry.

How does Stream detect duplicate values in a list?

Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.


1 Answers

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.

like image 111
Tunaki Avatar answered Sep 24 '22 06:09

Tunaki