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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With