Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading