Karthi Karthi - 2 months ago 9
Java Question

How to find the max value of an Arraylist and two of its Index position using Java

How can I find the maximum value from an

Arraylist
with its index positions?

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);


The above program just returns the output as the first max object with value
12
and index position
2
.

But my actual output should be index positions
2
and
4
(because max value
12
is present in two index position).

Answer

Untested:

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
Comments