どうも、ちょげ(@chogetarou)です。
Collections.min()でMap(マップ)の最小値のキー(Key)を取得する方法を紹介します。
方法

Collections.min()でMap(マップ)の最小値のキー(Key)を取得するには、2つの引数を使います。
まず、Collections.min()を呼び出します。
Collections.min()の第1引数にMapのentrySet()、第2引数に2つの引数を持つラムダ式を指定します。
第2引数のラムダ式で、第1引数のgetValue()から第2引数のgetValue()を引いた値を指定します。
そして、Collections.min()からgetKey()を呼び出します。
T minKey = Collections.min(map.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
上記のgetKey()は、Mapの最小値のキーを返します。
使用例
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Integer> numbers = new HashMap<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);
numbers.put("zero", 0);
numbers.put("four", 4);
numbers.put("five", 5);
String minKey = Collections.min(numbers.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
System.out.println(minKey);
}
}
出力:
zero
コメント