如何获得ArrayList中的最大值

Ng *_*oon 1 android compare arraylist

我想知道如何比较数组列表中的所有数组列表元素?例如,我想比较最大数字的元素。就像比较第 1 个元素和第 2 个元素一样,第 2 个元素与第 3 个元素进行比较。怎么做?

List <Product> productList= new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

谁能举例说明如何与这个变量进行比较?

productList.get(i).getPrice()
Run Code Online (Sandbox Code Playgroud)

感谢帮助。

Pus*_*dra 5

如果你只想要最大值,那么使用这个:

public int getMax(ArrayList list){
    int max = Integer.MIN_VALUE;
    for(int i=0; i<list.size(); i++){
        if(list.get(i) > max){
            max = list.get(i);
        }
    }
    return max;
}
Run Code Online (Sandbox Code Playgroud)

更好的方法是比较器:

public class compareProduct implements Comparator<Product> {
    public int compare(Product a, Product b) {
        if (a.getPrice() > b.getPrice())
            return -1; // highest value first
        if (a.getPrice() == b.getPrice())
            return 0;
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后就这样做:

Product p = Collections.max(products, new compareProduct());