我有一个存储不同数字的列表,它们中的最大值是索引下的元素:2; 4.
我想将这 2 个元素打印到控制台——作为数组中的最大数,但是 Collections.max() 方法只返回它找到的第一个最大值,即只返回索引 2 处的元素:
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(50);
numbers.add(12);
numbers.add(50);
System.out.println(Collections.max(numbers));
|Output|
50
我应该使用什么代替方法 Collections.max() 来查找所有最大值?
最佳答案
这使用一次迭代来找到它们
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(50);
numbers.add(12);
numbers.add(50);
int max = Integer.MIN_VALUE;
int count = 1;
for(int number : numbers){
if(number > max){
max = number;
count = 1;
} else if(number == max){
count++;
}
}
for(int i=0; i<count; i++){
System.out.println(max);
}
关于java - 如何在Java列表中找到所有最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68095082/