Streams and Collectors.toMap() – two approaches?

Among the below two code snippets – which one is preferable.

Approach -1

public Map<String, List<MyObj>> approach1(
            Iterable<? extends String> keys) {
        return StreamSupport.stream(keys.spliterator(), false)
                .map(dt -> new AbstractMap.SimpleEntry<>(dt, load(dt)))
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new));
    }

Approach – 2

public Map<String, List<MyObj>> approach2(
            Iterable<? extends String> keys)  {
        return StreamSupport.stream(keys.spliterator(), false)
                .collect(toMap(dt -> dt, k -> load(dt), (a, b) -> a, HashMap::new));
    }

In approach1, a map entry is explicitly created and then mapped in toMap using getKey and getValue, does this have any advantage or approach2 which is more direct is equally good.

Followup Question: If the entries in Iterable keys or not sorted, does the merge function (a, b) -> a give same result for the same entries in keys but in different order.

>Solution :

Based on the code you have provided, Both approaches will produce the same result.

The followup Question:
If the entries in Iterable keys are not sorted then the merge function (a, b) -> a may give different results depending on the order in which the entries are processed. This is because the merge function is used to resolve conflicts when two elements are mapped to the same key and the order may affect which element is retained in map,
if the keys are sorted then the merge function will give same result

Leave a Reply