Sorting Descending order: Java Map

前端 未结 5 1863
不思量自难忘°
不思量自难忘° 2020-12-05 04:28

What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but

相关标签:
5条回答
  • 2020-12-05 04:37

    You could simply invert the return value of your compare method by adding a minus sign at the beginning:

    return -((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
    
    0 讨论(0)
  • 2020-12-05 04:44
        TreeMap<Long,String> treeMap = new TreeMap<Long,String>();
    
        NavigableMap <Long, String> nmap = treeMap.descendingMap();
    
        Set<Long, String> set = nmap.entrySet();
    
        Iterator<Long, String> iterator = set.iterator();
    

    now u can iterate over iterator and extract the value using iterator.hasNext() and iterator.next() methods ......

    0 讨论(0)
  • 2020-12-05 04:54

    This will work :

          TreeMap<Integer, Integer> reverseInteger=new TreeMap<>(new Comparator<Integer>() {
    
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2>o1?1:o2==o1?0:-1;
            }
        });
    
    0 讨论(0)
  • 2020-12-05 04:55

    You should use new TreeMap<>(Collections.reverseOrder());.

    Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
    newMap.putAll(myMap);
    

    or to reverse an existing comparator like the value-comparator Collections.reverseOrder(comparator). It works like your approach swapping the two objects before invoking compare/compareTo.

    0 讨论(0)
  • 2020-12-05 04:58

    To change the solution in the link to sort by descending order, just reverse the condition:

    ...
    // Note: this comparator imposes orderings that are inconsistent with equals.    
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return 1; // For ascending, return -1;
        } else {
            return -1; // For ascending, return 1;
        } // returning 0 would merge keys
    }
    ...
    
    0 讨论(0)
提交回复
热议问题