Is there an easy way to get the max value from one field of an object in an arraylist of objects? For example, out of the following object, I was hoping to get the highest value for the Value field.
Example arraylist I want to get the max value for ValuePairs.mValue from.
ArrayList<ValuePairs> ourValues = new ArrayList<>();
outValues.add(new ValuePairs("descr1", 20.00));
outValues.add(new ValuePairs("descr2", 40.00));
outValues.add(new ValuePairs("descr3", 50.00));
Class to create objects stored in arraylist:
public class ValuePairs {
public String mDescr;
public double mValue;
public ValuePairs(String strDescr, double dValue) {
this.mDescr = strDescr;
this.mValue = dValue;
}
}
I'm trying to get the max value for mValue by doing something like (which I know is incorrect):
double dMax = Collections.max(ourValues.dValue);
dMax should be 50.00.
Then the length of the ArrayList can be found by using the size() function. After that, the first element of the ArrayList will be store in the variable min and max. Then the for loop is used to iterate through the ArrayList elements one by one in order to find the minimum and maximum from the array list.
In order to compute maximum element of ArrayList with Java Collections, we use the Collections. max() method.
In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.
Use a Comparator
with Collections.max()
to let it know which is greater in comparison.
Also See
Comparator
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With