Home >Java >javaTutorial >How Can I Efficiently Convert a Java List to a Map Using Streams and Lambdas?

How Can I Efficiently Convert a Java List to a Map Using Streams and Lambdas?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 13:38:10629browse

How Can I Efficiently Convert a Java List to a Map Using Streams and Lambdas?

Converting Java List to Map with Java 8 Streams and Lambdas

Background:

Converting a list of objects to a map is a common task. Java 7 and below require imperative coding using a for-each loop. In Java 8, using streams and lambdas provides a concise and elegant solution.

Java 7 Solution:

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

Java 8 Solution Without Guava:

Leveraging the Collectors class, the conversion can be done in a single stream operation:

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

Here, Choice::getName retrieves the name key, and Function.identity() preserves the value.

The above is the detailed content of How Can I Efficiently Convert a Java List to a Map Using Streams and Lambdas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn