Java Map Sort sortByDescendingValues(Map unsortMap)

Here you can find the source of sortByDescendingValues(Map unsortMap)

Description

Sort a map by values in descending order keeping the duplicate entries.

License

Apache License

Parameter

Parameter Description
map map to be sorted.

Declaration

public static Map sortByDescendingValues(Map unsortMap) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**//from   w ww  . ja  v  a  2 s. c  om
      * Sort a map by values in descending order keeping the duplicate entries.
      * @param map map to be sorted.
      */
    public static Map sortByDescendingValues(Map unsortMap) {

        List list = new LinkedList(unsortMap.entrySet());

        //sort list based on comparator
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return -((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());

            }
        });

        //put sorted list into map again
        Map sortedMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Related

  1. sortBy(Collection collection, final Map valuesMap)
  2. sortByComparator(Map unsortMap)
  3. sortByComparator(Map unsortMap)
  4. sortByComparatorDecreasing(Map unsortMap)
  5. sortByComparatorDouble( final Map map)
  6. sortByKey(final Map map, String order)
  7. sortByKey(Map map)
  8. sortByKey(T map, final boolean descending)
  9. sortByKeys( Map map)