Grouping Employees by City and Age
Categories: Java 8(JDK1.8) Java Java Examples
Grouping Employees by City and Age
package r4r.co.in;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class EmployeeGroupByCityAndAge {
public static void main(String[] args) {
//Grouping Employees by City
List<Employee> list = new ArrayList<Employee>();
list.add(new Employee("Rajesh", 121.0, "IT","Lucknow",24));
list.add(new Employee("Rani", 122.0, "ACT","NOIDA",35));
list.add(new Employee("Rahul", 122.0, "ACT","NOIDA",35));
list.add(new Employee("Rohit", 123.0, "ACT","Delhi",36));
list.add(new Employee("Sonu", 124.0, "OPR","Ambedkar Nagar",37));
System.out.println("Group by city--------");
Map<String, List<Employee>> groupByCity = list.stream().collect(Collectors.groupingBy(Employee::getCity));
System.out.println(groupByCity);
//Grouping Employees by Age
System.out.println("Group by age-------------");
Map<Integer ,List<Employee>> groupByAge=list.stream().collect(Collectors.groupingBy(Employee::getAge));
System.out.println(groupByAge);
}
}
class Employee {
String name;
double sal;
String dep;
String city;
int age;
public Employee(String name, double sal, String dep, String city,int age) {
super();
this.name = name;
this.sal = sal;
this.dep = dep;
this.city = city;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public String getDep() {
return dep;
}
public void setDep(String dep) {
this.dep = dep;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Employee [name=" + name + ", sal=" + sal + ", dep=" + dep + ", city=" + city + ", age=" + age + "]";
}
}