A Java 8 example to convert a List<?>
of objects into a Map<k, v>
1. POJO example
Hosting.java
package com.mkyong.java8
import java.util.Date;
public class Hosting {
private int Id;
private String name;
private Date createdDate;
public Hosting(int id, String name, Date createdDate) {
Id = id;
this.name = name;
this.createdDate = createdDate;
}
//getters and setters
}
2. Java 8 – Collectors.toMap()
Example to convert a List
into a stream, then collect it with Collectors.toMap
TestJava8.java
package com.mkyong.java8
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TestJava8 {
public static void main(String[] args) {
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", new Date()));
list.add(new Hosting(2, "linode.com", new Date()));
list.add(new Hosting(3, "digitalocean.com", new Date()));
//example 1
Map<Integer, String> result1 = list.stream().collect(
Collectors.toMap(Hosting::getId, Hosting::getName));
System.out.println("Result 1 : " + result1);
//example 2
Map<Integer, String> result2 = list.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));
System.out.println("Result 2 : " + result2);
}
}
Output
Result 1 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com}
Result 2 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com}
References
- Java 8 Collectors JavaDoc