Home >Java >javaTutorial >How Can I Efficiently Convert a Java List to a Map Using Streams and Lambdas?
Converting Java List
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!