Java 如何找到最大值的数组索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22911722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find array index of largest value?
提问by user3307418
The title above sums up my question, to clarify things an example is:
上面的标题总结了我的问题,为了澄清事情,一个例子是:
array[0] = 1
array[1] = 3
array[2] = 7 // largest
array[3] = 5
so the result I would like is 2, since it contains the largest element 7.
所以我想要的结果是 2,因为它包含最大的元素 7。
采纳答案by munyul
public int getIndexOfLargest( int[] array )
{
if ( array == null || array.length == 0 ) return -1; // null or empty
int largest = 0;
for ( int i = 1; i < array.length; i++ )
{
if ( array[i] > array[largest] ) largest = i;
}
return largest; // position of the first largest found
}
回答by ifloop
int maxAt = 0;
for (int i = 0; i < array.length; i++) {
maxAt = array[i] > array[maxAt] ? i : maxAt;
}
回答by Boris Brodski
public int getIndexOfMax(int array[]) {
if (array.length == 0) {
return -1; // array contains no elements
}
int max = array[0];
int pos = 0;
for(int i=1; i<array.length; i++) {
if (max < array[i]) {
pos = i;
max = array[i];
}
}
return pos;
}
回答by Shekhar Khairnar
one way will be:
一种方法是:
Integer[] array = new Integer[4];
array[0] = 1;
array[1] = 3;
array[2] = 7;
array[3] = 5;
List<Integer> iList = Arrays.asList(array);
System.out.println(iList.indexOf(Collections.max(iList)));
System.out.println(iList.indexOf(Collections.min(iList)));
回答by kimalser
Using Java 8 streams:
使用 Java 8 流:
List<Integer> list = Arrays.asList(1, 3, 7, 5);
IntStream.range(0, list.size())
.reduce((i, j) -> list.get(i) > list.get(j) ? i : j)
.getAsInt();
回答by kimalser
Two lines code will do that in efficient way
两行代码将以有效的方式做到这一点
//find the maximum value using stream API of the java 8
Integer max =Arrays.stream(numbers)?.max(Integer::compare).get();
// find the index of that value
int index = Arrays.asList(numbers).indexOf(max);
回答by Pratik Pawar
Please find below code for the same
请在下面找到相同的代码
Integer array[] = new Integer[4];
array[0] = 1;
array[1] = 3;
array[2] = 7;
array[3] = 5;
List < Integer > numberList = Arrays.asList(array);
int index_maxNumber = numberList.indexOf(Collections.max(numberList));
System.out.println(index_maxNumber);
回答by David Lilljegren
Another functional implementation
另一个功能实现
int array[] = new int[]{1,3,7,5};
int maxIndex =IntStream.range(0,array.length)
.boxed()
.max(Comparator.comparingInt(i -> array[i]))
.map(max->array[max])
.orElse(-1);