Home > Java > javaTutorial > How to Convert a Java 8 List to a Map Without Guava?

How to Convert a Java 8 List to a Map Without Guava?

Barbara Streisand
Release: 2024-12-29 08:37:14
Original
275 people have browsed it

How to Convert a Java 8 List to a Map Without Guava?

Java 8 List into Map without Guava

Java developers can utilize the power of Java 8 to convert a List into a Map without relying on third-party libraries like Guava.

Problem Statement

Consider the challenge of converting a List of objects into a Map using streams and lambdas in Java 8. The traditional approach in Java 7 and below involved iterating over the List and manually adding each element as a key-value pair to the Map.

Java 8 Solution

Java 8 provides a much simpler and elegant solution using the Collectors.toMap() method. This method takes two functions as arguments:

  • Key Mapper: A function that maps each element from the List to the key of the Map.
  • Value Mapper: A function that maps each element from the List to the value of the Map.

In this specific case, the key will be the name of each Choice object, and the value will be the Choice object itself. The stream().collect() method then collects the results into a Map using these functions.

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

This concise and efficient code snippet showcases the power of Java 8 streams and lambdas for transforming collections into different data structures.

The above is the detailed content of How to Convert a Java 8 List to a Map Without Guava?. 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