どうも、ちょげ(@chogetarou)です。
リスト(List)の最大値のインデックスを取得する方法を紹介します。
方法

リスト(List)の最大値のインデックスを取得する方法は、2つあります。
indexOf()
1つは、indexOf()を使う方法です。
まず、リストからindexOf()を呼び出します。
そして、indexOf()の引数に、リストの最大値を指定します。
int max = Collections.max(list); //最大値を取得
int maxIndex = list.indexOf(max); //最大値のインデックスを取得
上記のindexOf()は、呼び出したリスト(List)の最大値のインデックスを取得します。
使用例
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(2);
numbers.add(10);
numbers.add(44);
numbers.add(32);
numbers.add(17);
int max = Collections.max(numbers);
int maxIndex = numbers.indexOf(max);
System.out.println(maxIndex);
}
}
出力:
2
forループ
もう1つは、forループを使う方法です。
まず、最大値のインデックスを格納する変数を用意します。
次に、リストの要素数でforループします。
ループ変数のインデックスの要素と用意した変数のインデックスの要素を比較します。
そして、大きい要素の方のインデックスを変数に格納します。
//最大値のインデックスを格納する変数
int maxIndex = 0;
//list=任意のリスト
for (int i = 0; i < list.size(); i++) {
maxIndex = list.get(i) > list.get(maxIndex) ? i : maxIndex;
}
上記のforループは、用意した変数にリスト(List)の最大値のインデックスを格納します。
使用例
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(2);
numbers.add(10);
numbers.add(44);
numbers.add(32);
numbers.add(17);
int maxIndex = 0;
for (int i = 0; i < numbers.size(); i++) {
maxIndex = numbers.get(i) > numbers.get(maxIndex) ? i : maxIndex;
}
System.out.println(maxIndex);
}
}
出力:
2
まとめ
リスト(List)の最大値のインデックスを取得する方法は、次の2つです。
- indexOf()を使う方法
int max = Collections.max(list); //最大値を取得
int maxIndex = list.indexOf(max); //最大値のインデックスを取得
- forループを使う方法
コメント