user1474111
user1474111

Reputation: 1516

Collecting to HashMap to a LinkedHashMap in Java 8

I am converting HashMap to LinkedHashMap by using java 8 streams. I have the following code:

    final LinkedHashMap<String, Employee> collect = map.entrySet().stream()
            .sorted(Comparator.comparing(o -> o.getValue().getName()))
            .collect(Collectors.toMap(e -> e.getKey(), v -> v.getValue(), (o, o2) -> o, LinkedHashMap::new));

Everything is clear but the last parameter of the toMap method confuses me a lot.

(o, o2) -> o, LinkedHashMap::new)

As I understand that is a binaryOperator but I cannot understand how this works exactly and what 'o' means for o, LinkedHashMap::new

Can anyone help me to understand it or any better way to achieve this ?

Upvotes: 2

Views: 2384

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18919

(o, o2) -> o is the 3rd parameter

As the documentation says

@param mergeFunction a merge function, used to resolve collisions between * values associated with the same key, as supplied * to {@link Map#merge(Object, Object, BiFunction)}

This means that if you have a conflict you keep only o. You don't care about the other conflicting object o2. So o and o2 are 2 conflicting values that exist for the same key.

Upvotes: 2

Related Questions