English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 프로그램에서는 Java에서 주어진 맵을 값에 따라 정렬하는 방법을 배우게 됩니다.
import java.util.*; public class SortMap { public static void main(String[] args) { LinkedHashMap<String, String> capitals = new LinkedHashMap<>(); capitals.put("Nepal", "Kathmandu"); capitals.put("India", "New Delhi"); capitals.put("United States", "Washington"); capitals.put("England", "London"); capitals.put("Australia", "Canberra"); Map<String, String> result = sortMap(capitals); for (Map.Entry<String, String> entry : result.entrySet()) { System.out.print("Key: ", + entry.getKey()); System.out.println(" Value: ", + entry.getValue()); } } public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) { List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet()); Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2); LinkedHashMap<String, String> result = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } return result; } }
프로그램을 실행할 때, 출력은 다음과 같습니다:
Key: Australia Value: Canberra Key: Nepal Value: Kathmandu Key: England Value: London Key: India Value: New Delhi Key: United States Value: Washington
위의 프로그램에서, 우리는 LinkedHashMap 국가/지역과 각 지역의 수도가 변수 capitals에 저장되어 있습니다.
우리는 sortMap() 메서드를 가지고 있으며, 이 메서드는 양방향 링크드 목록을 받아 들여 정렬된 양방향 링크드 목록을 반환합니다.
메서드 내에서, 우리는 해시 맵을 목록 capitalList로 변환합니다. 그런 다음, sort() 메서드를 사용합니다. 이 메서드는 목록과 비교기를 받아 들입니다.
우리의 예제에서 비교기는 (o1,o2)-> o1.getValue().compareTo(o2.getValue()) 두 개의 목록 o1와 o2의 값을 비교하는 lambda 표현식.
연산 후, 정렬된 목록 capitalList를 얻습니다. 그런 다음, 목록을 LinkedHashMap 결과로 변환하여 반환하면 됩니다.
main() 메서드로 돌아가고, 맵의 각 항목을 순회하며 키와 값을 출력합니다.