问题
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).
回答1:
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
回答2:
You can use Collections to find the max value of a list, and then use the property indexOf to find its position in your list.
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)
回答3:
Just iterate once through list, have another list to push index of maximum number
回答4:
Since Java 8 this could be done by:
int index = IntStream.range(0, ar.size()).boxed()
.max(Comparator.comparing(ar::get)).orElse(-1);
回答5:
public static void main(String[] args){
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);
}
}
来源:https://stackoverflow.com/questions/10437623/how-to-find-the-max-value-of-an-arraylist-and-two-of-its-index-position-using-ja