Java Map Sort sortMapByValue(Map map, final boolean descending)

Here you can find the source of sortMapByValue(Map map, final boolean descending)

Description

sort Map By Value

License

Creative Commons License

Declaration

public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortMapByValue(Map<K, V> map,
            final boolean descending) 

Method Source Code

//package com.java2s;
//License from project: Creative Commons License 

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

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

public class Main {
    public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortMapByValue(Map<K, V> map) {
        return sortMapByValue(map, false);
    }//from  w ww  . j a  v a 2s.c o  m

    public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortMapByValue(Map<K, V> map,
            final boolean descending) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {

            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                int comp = (o1.getValue()).compareTo(o2.getValue());

                if (descending) {
                    comp = comp * (-1);
                }

                return comp;
            }
        });

        LinkedHashMap<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

Related

  1. sortMapByKey(Map map)
  2. sortMapByValue(Map input, final boolean desc)
  3. sortMapByValue(Map map, Comparator comparator)
  4. sortMapByValue(Map map, Comparator> valueComparator)
  5. sortMapByValue(Map map, Comparator> comparator)
  6. sortMapByValue(Map oriMap)
  7. sortMapByValue(Map unsortMap, boolean highFirst)
  8. sortMapByValue(Map oriMap)
  9. sortMapByValue(Map oriMap, final boolean isDesc)