Getting max value from an arraylist of objects?
This has been answered multiple time already, but since it's the first result on google I will give a Java 8 answer with an example.
Take a look at the stream feature. Then you can get the max form an List of Objects like this:
List<ValuePairs> ourValues = new ArrayList<>();
ourValues.stream().max(comparing(ValuePairs::getMValue)).get()
By the way in your example, the attributes should be private. You can then access them with a getter.
With Java 8 you can use stream()
together with it's predefined max()
function and Comparator.comparing()
functionality with lambda expression:
ValuePairs maxValue = values.stream().max(Comparator.comparing(v -> v.getMValue())).get();
Instead of using a lambda expression, you can also use the method reference directly:
ValuePairs maxValue = values.stream().max(Comparator.comparing(ValuePairs::getMValue)).get();
Use a Comparator
with Collections.max()
to let it know which is greater in comparison.
Also See
- How to use custom
Comparator