9

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?

1

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.