This example will show how to convert a list to a map using java, java 8 and guava. For the snippets below, we have created a Movie object. Typically when this this action occurs, the keys of the map are produced based on a specified object method and the values are the elements itself. In a related example we demonstrate how to transform a list to a map in groovy.
Setup
Straight up Java
When converting a list to a map using the core jdk, a traditional approach can be taken iterating over each element using a for each loop and calling the Map.put with a specified key and value.
Output
Java 8
Converting a list to a map in Java 8 can be performed by first converting the list to a stream and calling the collect terminal operation. In this instance, we will call Collectors.toMap which will return a collector that accumulates elements into a map. The keys are the generated from the Movie::getRank and the values are the Movie object.
Output
Google Guava
Guava Maps utility class contains Maps.uniqueIndex will create a map from a list of values. Each key is produced by calling a supplied function and the value is the value itself. Below, the function will pass in an object Movie and return an Integer by calling the Movie.getRank to create the Map.key.