ZAK ZAK:
私が持っているHashMap<Integer, Integer>
と私は、特定の値のキーを取得するつもりです。
例えば私のHashMap:
Key|Vlaue
2--->3
1--->0
5--->1
私は、最大値を持つキーを取得するには、Javaストリーム動作を探しています。この例では、キー2は、最大値を持っています。
だから、2はその結果である必要があります。
forループでそれが可能にすることができますが、私は、Javaストリーム方法を探しています。
import java.util.*;
public class Example {
public static void main( String[] args ) {
HashMap <Integer,Integer> map = new HashMap<>();
map.put(2,3);
map.put(1,0);
map.put(5,1);
/////////
}
}
彼らは次のとおりでした:
あなたは、エントリ上でストリーミングの最大値を検索し、対応するキーを返すことができます。
Integer maxKey =
map.entrySet()
.stream() // create a Stream of the entries of the Map
.max(Comparator.comparingInt(Map.Entry::getValue)) // find Entry with
// max value
.map(Map.Entry::getKey) // get corresponding key of that Entry
.orElse (null); // return a default value in case the Map is empty