Java - 从对象的arraylist获取最大值? [英] Java - getting max value from an arraylist of objects?

查看:123
本文介绍了Java - 从对象的arraylist获取最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以从对象的arraylist中的对象的一个​​字段中获取最大值?

Is there an easy way to get the max value from one field of an object in an arraylist of objects?

例如,出于以下对象,我我希望获得Value字段的最高值。

For example, out of the following object, I was hoping to get the highest value for the Value field.

示例arraylist我想从中获取ValuePairs.mValue的最大值。

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));

用于创建存储在arraylist中的对象的类:

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;

    }

}

我是试图通过做类似的事情来获取mValue的最大值(我知道这是不正确的):

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应该是50.00。

dMax should be 50.00.

任何帮助表示赞赏。谢谢!

Any help is appreciated. Thanks!

推荐答案

使用带比较器 ://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max%28java.util.Collection,%20java.util.Comparator%29rel =nofollow noreferrer> Collections.max() 让它知道哪个比较大。

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

另见

这篇关于Java - 从对象的arraylist获取最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆