Convert List of Object into single Map in Java
Example: Let we have a List of Object in java and we want to convert it into a single map based on two fields of each object as key and value pair.
Input: [{"name":"Rocky","age":23,"employeecode":1},{"name":"Aman","age":21,"employeecode":2},{"name":"Sam","age":19,"employeecode":4},{"name":"Peter","age":23,"employeecode":3}]
Output: {Rocky=23, Aman=21, Peter=23, Sam=19}
Approach-1 Using Java 8 stream API
Java
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class Employee {private String name;private Integer age;private Integer employeecode;//getters setters}public class BecomeCodeExpert {public static void main(String[] args) {Employee emp1 = new Employee();emp1.setName("Aman");emp1.setEmployeecode(1);emp1.setAge(21);Employee emp2 = new Employee();emp2.setName("Sam");emp2.setEmployeecode(2);emp2.setAge(19);Employee emp3 = new Employee();emp3.setName("Peter");emp3.setEmployeecode(3);emp3.setAge(23);Employee emp4 = new Employee();emp4.setName("Rocky");emp4.setEmployeecode(4);emp4.setAge(23);// This is the List of Employee Class that we have to// transform into Single MapList<Employee> employeeList = new ArrayList<>();employeeList.add(emp1);employeeList.add(emp2);employeeList.add(emp3);employeeList.add(emp4);System.out.println(employeeList);//code to convert List of object into single mapMap<String, Integer> emplMap = employeeList.stream().collect(Collectors.toMap(Employee::getName, Employee::getAge));System.out.println(emplMap);}}
Approach-2 Using for loop
Java
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class BecomeCodeExpert {public static void main(String[] args) {Employee emp1 = new Employee();emp1.setName("Aman");emp1.setEmployeecode(1);emp1.setAge(21);Employee emp2 = new Employee();emp2.setName("Sam");emp2.setEmployeecode(2);emp2.setAge(19);Employee emp3 = new Employee();emp3.setName("Peter");emp3.setEmployeecode(3);emp3.setAge(23);Employee emp4 = new Employee();emp4.setName("Rocky");emp4.setEmployeecode(4);emp4.setAge(23);// This is the List of Employee Class that we have to// transform into Single MapList<Employee> employeeList = new ArrayList<>();employeeList.add(emp1);employeeList.add(emp2);employeeList.add(emp3);employeeList.add(emp4);//code to convert List of object into single mapMap<String, Integer> emplMap = new HashMap<>();for(Employee employee:employeeList) {emplMap.put(employee.getName(), employee.getAge());}System.out.println(emplMap);}}
No comments:
Post a Comment