Java Map Sort sortMapByValues(Map map, final boolean inverted)

Here you can find the source of sortMapByValues(Map map, final boolean inverted)

Description

Borrowed from http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html Java method to sort Map in Java by value e.g.

License

Open Source License

Declaration

public static <K, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> map, final boolean inverted) 

Method Source Code

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

import java.util.*;

public class Main {
    /**// w  w w.  j a v a 2 s .  c  om
     * Borrowed from http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html
     * Java method to sort Map in Java by value e.g. HashMap or Hashtable
     * throw NullPointerException if Map contains null values
     * It also sort values even if they are duplicates
     */
    public static <K, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> map, final boolean inverted) {
        List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());

        Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {

            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                // Descending.
                if (!inverted)
                    return o2.getValue().compareTo(o1.getValue());
                else
                    return o1.getValue().compareTo(o2.getValue());
            }
        });

        //LinkedHashMap will keep the keys in the order they are inserted
        //which is currently sorted on natural ordering
        Map<K, V> sortedMap = new LinkedHashMap<K, V>();

        for (Map.Entry<K, V> entry : entries) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }
}

Related

  1. sortMapByValue(Map map, final boolean descending)
  2. sortMapByValue(Map oriMap)
  3. sortMapByValue(Map unsortMap, boolean highFirst)
  4. sortMapByValue(Map oriMap)
  5. sortMapByValue(Map oriMap, final boolean isDesc)
  6. sortMapByValuesDecreasing( final Map mapToSort)
  7. sortMapByValuesDescending( Map aMap)
  8. sortMapDesc(Map map)
  9. sortMapDescByValue(Map map)