1. TreeMap
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<>();
map.put("banana", 2);
map.put("apple", 5);
map.put("cherry", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
apple: 5
banana: 2
cherry: 3
2. HashMap + Stream API
HashMap
은 기본적으로 순서를 보장하지 않으므로 정렬된 결과를 얻으려면 LinkedHashMap
으로 결과 저장 필요
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("banana", 2);
map.put("apple", 5);
map.put("cherry", 3);
Map<String, Integer> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new
));
sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
apple: 5
banana: 2
cherry: 3
3. Comparator 로 사용자 정의 정렬(내림차순 정렬)
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("banana", 2);
map.put("apple", 5);
map.put("cherry", 3);
// 사용자 정의 정렬 (내림차순)
Map<String, Integer> sortedMap = map.entrySet()
.stream()
.sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new
));
sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
cherry: 3
banana: 2
apple: 5
4. TreeMap에 사용자 정의 Comparator 사용
TreeMap
을 생성할 때 Comparator
를 전달하여 키 정렬을 사용자 정의 가능
import java.util.*;
public class Main {
public static void main(String[] args) {
Comparator<String> reverseOrder = Comparator.reverseOrder();
Map<String, Integer> map = new TreeMap<>(reverseOrder);
map.put("banana", 2);
map.put("apple", 5);
map.put("cherry", 3);
map.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
cherry: 3
banana: 2
apple: 5