java – Java 8 List in the map

I want to translate a list of objects in a map using Java 8 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 do it easily using Java 8 and Guava but I’d like to know how to do it 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 lambda.

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

Leave a comment