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
Release: 2024-12-16 13:38:10
Original
626 people have browsed it

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;
}
Copy after login

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()));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template