Java 8 streams API handbook

Java 8 streams API handbook lists few example on converting list to map or map to list which is used in daily coding practices to reduce the line of code and make it more readable.

package prakshar;

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

public class Java8StreamAPIGuide {

public static void main(String[] args) {}

/** List into Map<K, V> **/
void ListToMap(List employees) {
Map<Integer, Employee> result = employees.stream().collect(Collectors.toMap(Employee::getDepartment, e -> e));
}

/** List into Map<K, List> **/
void ListToMapOfList(List employees) {
Map<Integer, List> result = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));
}

/** List into Map<K, V> on nested property **/
void ListToMap_onNestedProperty(List companies) {
Map<Employee, Company> result = companies.stream().collect(Collectors.toMap(Company::getCeo, e -> e));
}

/** List into Map<K, List> on nested property **/
void ListToMapOfList_onNestedProperty(List companies) {
Map<Integer, List> result = companies.stream().collect(Collectors.groupingBy( c -> c.getCeo().getDepartment()));
}

/** forEach **/
void forEach(List employees) {
     employees.forEach( emp -> {
          emp.setSalary(emp.getSalary()*1.1);
          if( emp.getDepartment()== 1)
                emp.setDepartment(5);
         });
}
} // end of class

class Company{
String name;
Employee ceo;
List workers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee getCeo() {
return ceo;
}
public void setCeo(Employee ceo) {
this.ceo = ceo;
}
public List getWorkers() {
return workers;
}
public void setWorkers(List workers) {
this.workers = workers;
}
}

class Employee{
String name;
int department;
double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDepartment() {
return department;
}
public void setDepartment(int department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
(Visited 26 times, 1 visits today)

PrAkAsH

Eyeing investment. Please note that the views given in this website are meant for reference and guidance of the readers to explore further on the topics and take informed decisions. These should not be construed as investment advice or legal opinion.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
36 ⁄ 9 =