Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 List<V> into Map<K, V>

I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

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; } 

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

private Map<String, Choice> nameMap(List<Choice> choices) {     return Maps.uniqueIndex(choices, new Function<Choice, String>() {          @Override         public String apply(final Choice input) {             return input.getName();         }     }); } 

And Guava with Java 8 lambdas.

private Map<String, Choice> nameMap(List<Choice> choices) {     return Maps.uniqueIndex(choices, Choice::getName); } 
like image 271
Tom Cammann Avatar asked Dec 03 '13 23:12

Tom Cammann


People also ask

Can we convert ArrayList to map in Java?

Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.

Can we convert List to map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

Can the value of a map be a List?

The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed: List of values and. List of keys from a Map.


1 Answers

Based on Collectors documentation it's as simple as:

Map<String, Choice> result =     choices.stream().collect(Collectors.toMap(Choice::getName,                                               Function.identity())); 
like image 122
zapl Avatar answered Sep 27 '22 20:09

zapl