Java Sorting a HashMap

Byul·2023년 6월 15일

Java

목록 보기
10/10
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
	map.put(i, (int) Math.ceil(Math.random() * 99));
}
int[] nums;
nums = 
	map.entrySet().stream(). // convert to a Stream to use stream API
    sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
    // sort by value on descending order 
    .limit(3) // get top 3 results
    .mapToInt(Map.Entry::getKey) // converts values to an IntStream
    .toArray(); // converts the IntStream to int[]
profile
junior backend developer

0개의 댓글