Java - 从对象的arraylist获取最大值? [英] Java - getting max value from an arraylist of objects?
问题描述
是否有一种简单的方法可以从对象的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!
推荐答案
Use a Comparator
with Collections.max()
to let it know which is greater in comparison.
另见
这篇关于Java - 从对象的arraylist获取最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!