Key 로 Sorting
treeMap 사용
TreeMap<String, Employee> sorted = new TreeMap<>(map);
ArrayList 사용
List<String> employeeByKey = new ArrayList<>(map.keySet());
Collections.sort(employeeByKey);
SortedSet<String> keySet = new TreeSet<>(map.keySet());
Stream 사용
map.entrySet()
.stream()
.sorted(Map.Entry.<String, Employee>comparingByKey())
.forEach(System.out::println);
Value 로 Sorting
List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.comparingByValue());
Map<K, V> result = new LinkedHashMap<>();
for (Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
ArrayList 사용
Comparator 사용
낮은순으로
List<Entry<Integer, Integer>> entryList = new LinkedList<>(map.entrySet());
entryList.sort(Map.Entry.comparingByValue(Comparator.naturalOrder()));
높은 순으로
List<Entry<Integer, Integer>> entryList = new LinkedList<>(map.entrySet());
entryList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
Stream 사용
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);
Map<String, Employee> result = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
'회고록 > Java dataStructure&Algorithm' 카테고리의 다른 글
| DFS (Def) feat 피로도 문제(프로그래머즈) (0) | 2024.03.19 |
|---|---|
| Overflow 문제. (피보나치 수) (1) | 2024.03.18 |
| Heap / PriorityQueue (0) | 2024.03.13 |
| java 진수 (base) 변경하기 (0) | 2024.03.11 |
| 소수(prime number) 인지 아닌지 확인. (0) | 2024.03.11 |