Jason Jason - 1 month ago 8
Java Question

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

Suppose I have the following

List
, which contains items of type
ENTITY
.
ENTITY
has an integer field which determines its natural ordering. I want to get the
ENTITY
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
//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.

Comments