Getting maximum value from arraist objects?

Is there an easy way to get the maximum value from a single field of an object in an arraylist of objects?

For example, from the following object, I was hoping to get the maximum value for the Value field.

Arraylist example I want to get the maximum value for ValuePairs.mValue.

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 for creating 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 am trying to get the maximum value for mValue by doing something like (which I know is incorrect):

double dMax = Collections.max(ourValues.dValue);

dMax should be 50.00.

Any help is appreciated. Thanks!

+4
source share
4 answers

Use Comparatorwith Collections.max()to find out what is more in comparison.


Also see

+10

, google, Java 8 .

stream. List of Objects, :

List<ValuePairs> ourValues = new ArrayList<>();

ourValues.stream().max(comparing(ValuePairs::getMValue)).get()

, . .

+3

, / O(N). , PriorityQueue O(1), .

0
source

With Java 8, you can use stream()a predefined function with it max()and Comparator.comparing()with the help of a lambda expression:

ValuePairs maxValue = values.stream().max(Comparator.comparing(v -> v.getMValue())).get();
0
source

All Articles