Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting max value from an arraylist of objects?

Tags:

java

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.

like image 803
user797963 Avatar asked Oct 12 '13 20:10

user797963


People also ask

How do you find the max and min of an ArrayList in Java?

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.

How do you find the max value in an ArrayList?

In order to compute maximum element of ArrayList with Java Collections, we use the Collections. max() method.

How do you find the min of an ArrayList?

In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.


2 Answers

Use a Comparator with Collections.max() to let it know which is greater in comparison.


Also See

  • How to use custom Comparator
like image 161
jmj Avatar answered Sep 30 '22 16:09

jmj


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();
like image 30
M. Schena Avatar answered Sep 30 '22 17:09

M. Schena