The following demonstrates 4 possible solutions. Note the comments:
import java.util.*;
public class Main{
public static void main(String[] args) {
//Hardcoded data to make it more of an mre
List<EmployeesDetails> employeesDetails = new ArrayList<>();
employeesDetails.add(new EmployeesDetails("Sara", 1000f));
employeesDetails.add(new EmployeesDetails("Deby", 1400f));
employeesDetails.add(new EmployeesDetails("Dan", 1200f));
//solution 1
//Iterate over the collection and keep the employee with the highest (you can also keep the lowest)
EmployeesDetails highestSalary = employeesDetails.get(0);
for(EmployeesDetails e :employeesDetails ){
if(e.getEmpSalary() > highestSalary.getEmpSalary()){
highestSalary = e;
}
}
//solution 2 contributed by Charlie Armstrong
//Use Collections.max ( Collections.min )
EmployeesDetails empD = Collections.max(employeesDetails, (e1, e2) -> Float.compare(e1.getEmpSalary(), e2.getEmpSalary()));
System.out.println("employee with highest salary is "+empD);
//solution 3
//Use a stream, sort by salary find first to get the lowest
//sort by salary in reverse and find first to get the highest
Optional<EmployeesDetails> opEmpD = employeesDetails.stream().sorted((e1, e2) -> Float.compare(e2.getEmpSalary(), e1.getEmpSalary())).findFirst();
System.out.println( opEmpD == null ? "No solution found" : "employee with highest salary is "+opEmpD.get());
System.out.println("employee with highest salary is "+ highestSalary);
//solution 4
//Sort the collection by salary the last one is the highest
//(get the first one for the lowest)
Collections.sort(employeesDetails, (e1, e2) -> Float.compare(e1.getEmpSalary(), e2.getEmpSalary()));
System.out.println("employee with highest salary is "+ employeesDetails.get(employeesDetails.size()-1));
}
}
//simplified for to make it more of an mre
class EmployeesDetails {
private final String empName;
private final Float empSalary;
public EmployeesDetails(String empName, Float empSalary) {
this.empName = empName;
this.empSalary = empSalary;
}
@Override
public String toString() {
return "EmployeesDetails{" +
"Name='" + empName + '\'' +
", Salary='" + empSalary+ '\'' +
'}';
}
public String getEmpName() {
return empName;
}
public Float getEmpSalary() {
return empSalary;
}
}
See:
https://stackoverflow.com/help/minimal-reproducible-example