× - 코드 및 콘솔 화면은 [ code ] 내용 [ /code ] 태그 처리하여 주세요.
- 강조하고자 하는 내용은 [ b ] 내용 [ /b ] 태그 처리하여 주세요.

TreeMap을 값 기준으로 정렬하는 방법은?

  • minjoo
    (minjoo)
  • minjoo's Avatar 이 글의 작성자
  • Offline
  • Newbie
  • Newbie
더보기
03 Jun 2016 15:59 #672 작성자: minjoo
minjoo 님의 글: TreeMap을 값 기준으로 정렬하는 방법은?
Map 타입 중 정렬(sort)을 위해 TreeMap을 종종 사용하곤 하는데요.. 혹시 키가 아닌 값 기준으로 정렬할 수 있는 방법이 있을까요?? 구글링을 해봐도 자체적인 메소드는 없는것 같은데 그런 역할을 하는 메소드를 따로 만들어서 사용하는 방법말고는 없는지 궁금합니다.
  • bbparkk
    (주말만기다려)
  • bbparkk's Avatar
  • Offline
  • Newbie
  • Newbie
더보기
09 Sep 2016 20:31 - 09 Sep 2016 20:31 #1187 작성자: bbparkk
bbparkk 님의 답글: TreeMap을 값 기준으로 정렬하는 방법은?
stackoverflow.com/questions/2864840/treemap-sort-by-value
static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
        new Comparator<Map.Entry<K,V>>() {
            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                int res = e1.getValue().compareTo(e2.getValue());
                return res != 0 ? res : 1;
            }
        }
    );
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}
Time to create page: 0.052 seconds
Powered by Kunena Forum