How to transform a List to Map by using java 8 lambda and stream or Guava
This post would demo how to transform a List to Map by using java 8 lambda and stream or Guava.
This example will include:
- How to transform a List to Map by using java 7 old style
- How to transform a List to Map by using Guava Maps.uniqueIndex and java 8 lambda
- How to transform a List to Map by using java 8 stream
- Java 1.8
2. Example codes
2.1 Setup a class to be used as POJO object
This is an inner class named Game,which has two properties: name and price.
- It has a constructor with params
- It has a toString for print purpose
2.2 How to transform a List to Map by using java 7 old style
Before we try the java 8 style, let’s review the java 7 old style:
We just use the game’s name as the map key and the game object as the value,that is:
Game.getName() –> Game Object
2.3 How to transform a List to Map by using Guava Maps.uniqueIndex and java 8 lambda
Guava supply a uniqueIndex method to transform a List to a Map, the method is:
public static <K,V> ImmutableMap<K,V> uniqueIndex(Iterable
values,Function<? super V,K> keyFunction)
Returns a map with the given values, indexed by keys derived from those values. In other words, each input value produces an entry in the map whose key is the result of applying keyFunction to that value. These entries appear in the same order as the input values.
It just need two params:
- The values, may be a List
- The keyFunction, tranform from the value to a Key
Add the guava dependency to pom.xml
Then write the examples:
We write two examples:
- The first one use Maps.uniqueIndex by supply a lambda expression
- The second one use Maps.uniqueIndex by supply a method reference
2.4 How to transform a List to Map by using java 8 stream
Here we use the Collectors.toMap to do the trick, the Collectors.toMap method definition is:
public static <T, K, U> Collector<T, ?, Map<K,U» toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper)
Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
2.5 Run the examples
And we got this result:
As you can see, all kinds of transform has the same result.
In this post we demo how to tranform a List to a Map by using various methods.You can find the whole code examples on github.
You can find detail documents about the java stream here: