write a program to convert List to Map using Java 8?
In this program convert List to Map using Java8.here we are use a Department model class.then create ListToMap class to call Stream API. Collectors.toMap method convert list to Map data.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Department {
private int id;
private String name;
private long websites;
public Department(int id, String name, long websites) {
super();
this.id = id;
this.name = name;
this.websites = websites;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getWebsites() {
return websites;
}
public void setWebsites(long websites) {
this.websites = websites;
}
@Override
public String toString() {
return "Hosting [id=" + id + ", name=" + name + ", websites=" + websites + "]";
}
}
public class ListToMap {
public static void main(String[] args) {
List l = new ArrayList();
l.add(new Department(1, "san.com", 12455));
l.add(new Department(2, "skjh.com", 598700));
l.add(new Department(3, "wesd.com", 10000));
l.add(new Department(4, "tyui.com", 20000));
l.add(new Department(5, "wesd.com", 110000));
Map m = l.stream().collect(Collectors.toMap(Department::getId, Department::getName));
System.out.println(m);
Map
Output :-
{1=san.com, 2=skjh.com, 3=wesd.com, 4=tyui.com, 5=wesd.com}
{1=12455, 2=598700, 3=10000, 4=20000, 5=110000}
{tyui.com=20000, wesd.com=10000, san.com=12455, skjh.com=598700}
————————-
{stud.com=200000, javatechnote.com=120000, xyz.com=100000, testode.com=90000, lightweb.com=80000, learn.com=1}
write a program to convert List to Map using Java 8? Read More »