Jason Jason - 3 years ago 101
Java Question

Sorting a list based on a field on each of its members

Suppose I have the following

, which contains items of type
has an integer field which determines its natural ordering. I want to get the
which is the maximum or minimum based on that field's value. How can I implement this in Java?

List<ENTITY> lt = new ArrayList<ENTITY>();

class ENTITY
int field;
/* Constructor, getters, setters... */

Answer Source
//stream the elements, map to their fields, and get the max
return lt.stream().max((e1, e2) -> Integer.compare(e1.filed, e2.filed)).orElse(/* default */);

Just one of the many applications of Java 8's stream api.

Though I would suggest working on some coding conventions first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download