Java Map Sort sortMapByValue(Map input, final boolean desc)

Here you can find the source of sortMapByValue(Map input, final boolean desc)

Description

sort Map By Value

License

Apache License

Declaration

public static <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> input, final boolean desc) 

Method Source Code


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

import java.util.*;

public class Main {
    public static <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> input, final boolean desc) {
        LinkedHashMap<K, V> output = new LinkedHashMap<K, V>(input.size());
        ArrayList<Map.Entry<K, V>> entryList = new ArrayList<Map.Entry<K, V>>(input.size());
        Collections.sort(entryList, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                if (desc)
                    return o2.getValue().compareTo(o1.getValue());
                return o1.getValue().compareTo(o2.getValue());
            }//from   w w  w .  jav  a2  s  .co  m
        });
        for (Map.Entry<K, V> entry : entryList) {
            output.put(entry.getKey(), entry.getValue());
        }

        return output;
    }

    public static <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> input) {
        return sortMapByValue(input, true);
    }
}

Related

  1. sortMap(Map oldMap, final boolean asc)
  2. sortMap(Map map, int k)
  3. sortMap(Map map, Comparator> compator)
  4. sortMapByKey(Map data)
  5. sortMapByKey(Map map)
  6. sortMapByValue(Map map, Comparator comparator)
  7. sortMapByValue(Map map, Comparator> valueComparator)
  8. sortMapByValue(Map map, Comparator> comparator)
  9. sortMapByValue(Map map, final boolean descending)