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