HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Java 8 List<V> into Map<K, V>

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
listintojavamap

Problem

I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below:

private Map nameMap(List choices) {
    final Map hashMap = new HashMap<>();
    for (final Choice choice : choices) {
        hashMap.put(choice.getName(), choice);
    }
 
    return hashMap;
}


I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

private Map nameMap(List choices) {
    return Maps.uniqueIndex(choices, new Function() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }

    });
}


And Guava with Java 8 lambdas:

private Map nameMap(List choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}

Solution

Based on Collectors documentation it's as simple as:

Map result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));

Code Snippets

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));

Context

Stack Overflow Q#20363719, score: 1539

Revisions (0)

No revisions yet.