-1

如何从Arraylist索引位置找到最大值?

ArrayList ar = new ArrayList();
ar.add(2); // position 0
ar.add(4); // position 1
ar.add(12); // position 2
ar.add(10); // position 3
ar.add(12); // position 4

String obj = Collections.max(ar);
int index = ar.indexOf(obj);

System.out.println("obj max value is " + obj + " and index position is " + index);

上面的程序只是将输出作为具有 value12和 index position的第一个 max 对象返回2

但我的实际输出应该是索引位置24(因为最大值12存在于两个索引位置)。

4

5 回答 5

5

您可以使用Collections查找列表的最大值,然后使用属性indexOf查找其在列表中的位置。

List<Integer> myList = new ArrayList<Integer>();
myList.add(3); // adding some values
myList.add(5);
myList.add(7);
myList.add(3);
myList.add(1);

Integer maxVal = Collections.max(myList); // should return 7
Integer maxIdx = myList.indexOf(maxVal); // should return 2 (position of the value 7)
于 2018-10-26T14:29:07.167 回答
3

从 Java 8 开始,这可以通过以下方式完成:

int index = IntStream.range(0, ar.size()).boxed()
        .max(Comparator.comparing(ar::get)).orElse(-1);
于 2019-03-12T11:58:08.380 回答
1

只需遍历列表一次,有另一个列表来推送最大数量的索引

于 2012-05-03T18:56:08.297 回答
1

未经测试:

public static int maxIndex(List<Integer> list) {
  Integer i=0, maxIndex=-1, max=null;
  for (Integer x : list) {
    if ((x!=null) && ((max==null) || (x>max))) {
      max = x;
      maxIndex = i;
    }
    i++;
  }
  return maxIndex
}
// ...
maxIndex(Arrays.asList(1, 2, 3, 2, 1)); // => 2
maxIndex(Arrays.asList(null, null)); // => -1
maxIndex(new ArrayList<Integer>()); // => -1
于 2012-05-03T19:09:08.170 回答
0

公共静态无效主要(字符串[]参数){

    List<Integer> ar=new ArrayList<Integer>();
    ar.add(2); `adding the values in the list`
    ar.add(5);
    ar.add(6);
    ar.add(4);
    ar.add(6);
    ar.add(5);
    ar.add(6);

    int max=Collections.max(ar);

    while(ar.contains(max))
    {
        int i=ar.indexOf(max); 
        System.out.println("the index of 6:"+ar.indexOf(max));
        ar.set(i, -1);
        System.out.println(ar);
    }       

}

于 2012-05-04T08:28:57.693 回答