Wednesday, 9 May 2018


Java Stream Example : Convert List into Map


package conversionlist;

public class Employee {
               
                int eid;
                String ename;
                float esalary;
                public Employee(int eid, String ename, float esalary) {
                                super();
                                this.eid = eid;
                                this.ename = ename;
                                this.esalary = esalary;
                }
                }
package conversionlist;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class EmployeeMain {
               
                public static void main(String[] args) {
                                List<Employee> l=new ArrayList<Employee>();
                                Employee e1=new Employee(101, "govind", 18000.00f);
                                Employee e2=new Employee(102, "ajit", 55000.00f);
                                Employee e3=new Employee(103, "mani", 46000.00f);
                                Employee e4=new Employee(104, "dinesh", 16000.00f);
                                Employee e5=new Employee(105, "rajan", 48000.00f);
                                l.add(e1);
                                l.add(e2);
                                l.add(e3);
                                l.add(e4);
                                l.add(e5);
                               
                                Map<Integer,String> m = l.stream()
                                                                .collect(Collectors.toMap(e->e.eid, e->e.ename));
                                System.out.println(m);
                               
                }
}
o/p:--------------------
{101=govind, 102=ajit, 103=mani, 104=dinesh, 105=rajan}

No comments:

Post a Comment