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