Java Map Sort sortMapDescByValue(Map map)

Here you can find the source of sortMapDescByValue(Map map)

Description

sort Map Desc By Value

License

Open Source License

Declaration

public static Map<String, Integer> sortMapDescByValue(Map<String, Integer> map) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Collections;
import java.util.Comparator;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static Map<String, Integer> sortMapDescByValue(Map<String, Integer> map) {
        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());

        // sort list based on comparator
        Collections.sort(list, new Comparator<Entry<String, Integer>>() {
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }// w  w w  .  ja v  a 2 s. c  om
        });

        // put sorted list into map again
        //LinkedHashMap make sure order in which keys were inserted
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Iterator<Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
            Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Related

  1. sortMapByValue(Map oriMap, final boolean isDesc)
  2. sortMapByValues(Map map, final boolean inverted)
  3. sortMapByValuesDecreasing( final Map mapToSort)
  4. sortMapByValuesDescending( Map aMap)
  5. sortMapDesc(Map map)
  6. sortMapDescendingByValue(Map unsortedMap)
  7. sortMapUsingComparator(final Map map, final Comparator comparator)
  8. sortParams(Map params)
  9. sortSimilarityMapByValue(SortedMap temp)