如何从集合中获取最大值(例如ArrayList)?

2022-08-31 07:35:10

有一个存储整数值的 ArrayList。我需要在此列表中找到最大值。例如,假设 arrayList 存储的值为 :,最大值为 。10, 20, 30, 40, 5050

找到最大值的有效方法是什么?

@Edit :我只是找到了一个我不太确定的解决方案

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/

Integer i = Collections.max(arrayList)

这将返回最大值。

比较每个值的另一种方法,例如selection sort or binary sort algorithm  


答案 1

您可以使用 它来轻松实现您想要的 - 高效阅读 - 足够的Javadoc用于集合.maxCollections API

Collections.max(arrayList);

根据其元素的自然顺序,返回给定集合的最大元素。集合中的所有元素都必须实现可比较接口。


答案 2

这个问题已经存在了将近一年,但我发现,如果您为对象创建自定义比较器,则可以使用Collections.max用于对象的数组列表。

import java.util.Comparator;

public class compPopulation implements Comparator<Country> {
    public int compare(Country a, Country b) {
        if (a.getPopulation() > b.getPopulation())
            return -1; // highest value first
        if (a.getPopulation() == b.Population())
            return 0;
        return 1;
    }
}
ArrayList<Country> X = new ArrayList<Country>();
// create some country objects and put in the list
Country ZZ = Collections.max(X, new compPopulation());

推荐