Reputation: 407
I need to retrieve the highest value from a List of Class. Yet, I have been using Collections.max(list)
while retrieving data from an ArrayList, but not able to recall if there is any class to do same from List of Class.
I have a Class:
public Class Emp{
private Integer empno;
private String empName;
private Float salary;
}
Using Spring - Hibernate, I am retrieving whole table in an List<Emp>
.
DAO code is:
public List<Emp> retriveAllEmp(){
return getSession().createQuery("from Emp");
}
Note: In actual application, the data is inserted into Emp class using complicated queries and later displayed to client.
Requirement is to get the max of salary.
Yet this can be done by query or Criteria on Emp object like
Float maxSalary = getSession().createQuery("select max(salary) from Emp");
or by running a loop on the List.
But can we use any collection methods to do same or any other alternative approach?
Upvotes: 0
Views: 2045
Reputation: 48864
It's not very clear what you're asking, but I think you're trying to say:
I've used
Collections.max(Collection<T>)
on aList<Float>
before, but I don't know how to get the maximum from a custom object like myEmp
class.
Assuming I'm correctly interpreting your question, the answer is to use the other max()
method, Collections.max(Collection<T>, Comparator<T>)
. This method takes a Comparator
in addition to the collection you want to search, so that you can provide an explicit ordering for your Emp
objects.
The code would look something like this:
List<Emp> results = ...;
Emp max = Collections.max(results, new Comparator<Emp>() {
int compare(Emp a, Emp b) {
return Float.compare(a.getSalary(), b.getSalary());
}
});
Upvotes: 2
Reputation: 21
As pickypg said, implement Compactor interface which compares the salary. Then call Collection's max method to get maximum salary. Simple.
Upvotes: 0