Sunday, 15 March 2020

Convert list to map using streams

Using 'Collectors.toMap' method we can convert list of objects to a map.

Example
Map<String, String> map =emps.stream().collect(Collectors.toMap(Employee::getFirstName, Employee::getLastName));

Employee.java
package com.sample.app.model;

public class Employee {
 private String firstName;
 private String lastName;

 public Employee(String firstName, String lastName) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
  result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (firstName == null) {
   if (other.firstName != null)
    return false;
  } else if (!firstName.equals(other.firstName))
   return false;
  if (lastName == null) {
   if (other.lastName != null)
    return false;
  } else if (!lastName.equals(other.lastName))
   return false;
  return true;
 }

}

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.sample.app.model.Employee;

public class App {
 
 public static void main(String args[]) throws InterruptedException {
  Employee emp1 = new Employee("Ram", "Gurram");
  Employee emp2 = new Employee("Siva", "Ponnam");
  Employee emp3 = new Employee("Sailaja", "Navakotla");
  Employee emp4 = new Employee("Gopi", "Battu");
  
  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4);
  
  Map<String, String> map =emps.stream().collect(Collectors.toMap(Employee::getFirstName, Employee::getLastName));
  
  for(String firstName: map.keySet()) {
   System.out.println(firstName + " , " + map.get(firstName));
  }
 }

}

Output

Gopi , Battu
Sailaja , Navakotla
Siva , Ponnam
Ram , Gurram


You may like

No comments:

Post a Comment