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<Department> l = new ArrayList<Department>();
		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<Integer, String> m = l.stream().collect(Collectors.toMap(Department::getId, Department::getName));
		System.out.println(m);
		Map<Object, Object> h = l.stream().collect(Collectors.toMap(x -> x.getId(), s -> s.getWebsites()));
		System.out.println(h);
		Map<String, Long> z = l.stream().collect(
				Collectors.toMap(Department::getName, Department::getWebsites, (oldValue, newValue) -> oldValue));
		System.out.println(z);
		System.out.println("-------------------------");
		List<Department> list = new ArrayList<>();
		list.add(new Department(1, "lightweb.com", 80000));
		list.add(new Department(2, "testode.com", 90000));
		list.add(new Department(3, "javatechnote.com", 120000));
		list.add(new Department(4, "stud.com", 200000));
		list.add(new Department(5, "learn.com", 1));
		list.add(new Department(6, "xyz.com", 100000));
		Map response = list.stream().sorted(Comparator.comparingLong(Department::getWebsites).reversed())
				.collect(Collectors.toMap(Department::getName, Department::getWebsites,
						(oldValue, newValue) -> oldValue, LinkedHashMap::new));
		System.out.println(response);
	}
}
				
			

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 »