본문 바로가기
회고록/Java dataStructure&Algorithm

map 정열/Sorting by key or value

by sehunbang 2024. 3. 15.

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));