如何从List / ArrayList获取最大值 [英] how to get maximum value from the List/ArrayList
问题描述
有一个存储整数值的ArrayList。我需要在此列表中找到最大值。例如。假设arrayList存储的值是: 10,20,30,40,50
,最大
值将是 50
。
There is an ArrayList which stores integer values. I need to find the maximum value in this list. E.g. suppose the arrayList stored values are : 10, 20, 30, 40, 50
and the max
value would be 50
.
找到最大值的有效方法是什么?
What is the efficient way to find the maximum value?
@Edit: 我刚找到一个我不太确定的解决方案
@Edit : I just found one solution for which I am not very sure
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/
Integer i = Collections.max(arrayList)
这将返回最高值。
比较每个值的另一种方法例如选择排序或二进制排序算法
Another way to compare the each value e.g. selection sort or binary sort algorithm
推荐答案
您可以使用 Collections API
轻松实现您的目标 - 高效阅读 - 足够
Javadoc for Collections.max
You can use the Collections API
to achieve what you want easily - read efficiently - enough
Javadoc for Collections.max
Collections.max(arrayList);
根据自然顺序返回给定集合的最大元素它的元素。集合中的所有元素都必须实现Comparable接口。
Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface.
这篇关于如何从List / ArrayList获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!