Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create HashMap with streams overriding duplicates?

I'm creating a HashMap using java8 stream API as follows:

Map<Integer, String> map = dao.findAll().stream()
    .collect(Collectors.toMap(Entity::getType, Entity::getValue));

Now if an element is added to the collection where the key already exists, I just want to keep the existing element in the list and skip

the additional element. How can I achieve this? Probably I have to make use of BinaryOperation<U> of toMap(), but could anyone provide

an example of my specific case?

like image 765
membersound Avatar asked Mar 24 '15 16:03

membersound


1 Answers

Yes, you need that BinaryOperation<U> and use it as a third argument for Collectors.toMap().

In case of a conflict (appearance of an already existing key) you get to choose between value oldValue (the existing one) and newValue. In the code example we always take value oldValue. But you are free to do anything else with these two values (take the larger one, merge the two etc.).

The following example shows one possible solution where the existing value always remains in the map:

Map<Integer, String> map = dao.findAll().stream()
     .collect(Collectors.toMap(Entity::getType, Entity::getValue, (oldValue, newValue) -> oldValue));

See the documentation for another example.

like image 152
reto Avatar answered Oct 17 '22 03:10

reto