How to get max and second max salary using Java 8

 


    In  this  example  will   learn   how  to get max  and  second  max    salary  

    from an employee list.




import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;

import java.util.ArrayList;


public class FindMaxSalaryEmployee {


public static void main(String[] args) {

List<EmployeeMax> EmployeeMaxs = new ArrayList<>();

EmployeeMaxs.add(new EmployeeMax("Monu", 32, 77000));

EmployeeMaxs.add(new EmployeeMax("Sonu", 30, 50000));

EmployeeMaxs.add(new EmployeeMax("Eklu", 35, 40000));

EmployeeMaxs.add(new EmployeeMax("Viru", 28, 30000));

EmployeeMaxs.add(new EmployeeMax("Pri", 20, 35000));


/*

* List<EmployeeMax> sortedList = EmployeeMaxs.stream()

* .sorted(Comparator.comparingInt(EmployeeMax::getSalary)

.reversed()).collect(Collectors.toList());

*/


List<EmployeeMax> sortedList = 

EmployeeMaxs.stream().sorted(Comparator.comparingInt(EmployeeMax::getSalary).reversed()).collect(Collectors.toList());


System.out.println("Seceond Max"+sortedList.get(1));

System.out.println(" Max salary"+sortedList.get(0));

 sortedList.forEach(EmployeeMax -> System.out.println("Employee salary " +

  EmployeeMax.getSalary()));

 



}


}




 EmployeeMax.java


 

  public class EmployeeMax {

  private  String  name ; 

  private    int age;

  private   int salary ;

  

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public int getSalary() {

return salary;

}

public void setSalary(int salary) {

this.salary = salary;

}


public EmployeeMax(String name, int age, int salary) {

super();

this.name = name;

this.age = age;

this.salary = salary;

}

@Override

public String toString() {

return "EmployeeMax [name=" + name + ", age=" + age + ", salary=" + salary + "]";

}




}

 Programm  output 

 -----------------


   Seceond MaxEmployeeMax [name=Sonu, age=30, salary=50000]

 Max salaryEmployeeMax [name=Monu, age=32, salary=77000]

Employee salary 77000

Employee salary 50000

Employee salary 40000

Employee salary 35000

Employee salary 30000





How to get max and second max salary using Java 8    How to  get  max  and  second  max  salary    using Java 8 Reviewed by Mukesh Jha on 10:52 PM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.