java - How can I retrieve all of the maximum values from a list? -
i have class called employee
implements comparable
interface.
now have 5 employee
objects in list, each of has own salary
property. want find of employee
objects have max salary.
i can single object using
employee employee = collections.max(employeelist);
but returns single employee
, while trying retrieve array or list of of objects same max value. how can this?
to efficient, should iterate through list , find max elements yourself:
list<employee> result = new arraylist<>(); employee currentmax = null; (employee e : list) { if (currentmax == null || e.compareto(currentmax) > 0) { currentmax = e; result.clear(); result.add(e); } else if (currentmax!= null && e.compareto(currentmax) == 0) { result.add(e); } }
this solution o(n), , requires single pass through list.