[Java]リスト(List)の最小値のインデックスを取得するには?

Java

どうも、ちょげ(@chogetarou)です。

リスト(List)の最小値のインデックスを取得する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

リスト(List)の最小値のインデックスを取得する方法は、2つあります。

indexOf()

1つは、indexOf()を使う方法です。

まず、リストからindexOf()を呼び出します。

そして、indexOf()の引数に、リストの最小値を指定します。

int min = Collections.min(list); //最小値を取得
int minIndex = list.indexOf(min); //最小値のインデックスを取得

上記の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(0);
        numbers.add(17);
        
        int min = Collections.min(numbers);
        int minIndex = numbers.indexOf(min);
        
        System.out.println(minIndex);
    }
}
出力:
4

forループ

もう1つは、forループを使う方法です。

まず、最小値のインデックスを格納する変数を用意します。

次に、リストの要素数でforループします。

ループ変数のインデックスの要素と用意した変数のインデックスの要素を比較します。

そして、小さい要素の方のインデックスを変数に格納します。

//最小値のインデックスを格納する変数
int minIndex = 0;

for (int i = 0; i < list.size(); i++) {
    minIndex = list.get(i) < list.get(minIndex) ? i : minIndex;
}

上記のforループは、用意した変数にリスト(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(0);
        numbers.add(17);
        
        int minIndex = 0;
        for (int i = 0; i < numbers.size(); i++) {
            minIndex = numbers.get(i) < numbers.get(minIndex) ? i : minIndex;
        }
        
        System.out.println(minIndex);
    }
}
出力:
4

まとめ

リスト(List)の最小値のインデックスを取得する方法は、次の2つです。

  • indexOf()を使う方法
    int min = Collections.min(list); //最小値を取得
    int minIndex = list.indexOf(min); //最小値のインデックスを取得
  • forループを使う方法

コメント

タイトルとURLをコピーしました