Java Map Sort sortByValue(Map map)

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

Description

Sort the value in the map and swap the pair of view and its rank value in descending order.

License

Open Source License

Parameter

Parameter Description
map the map to be sorted

Return

the sorted map

Declaration

public static <K extends Object, V extends Object> Map<K, V> sortByValue(Map<K, V> map) 

Method Source Code


//package com.java2s;
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;

public class Main {
    /**//  ww  w.  ja v  a  2 s . co  m
     * Sort the value in the map and swap the pair of view
     * and its rank value in descending order.
     * 
     * @param map the map to be sorted
     * @return the sorted map
     */
    public static <K extends Object, V extends Object> Map<K, V> sortByValue(Map<K, V> map) {
        return sortByValue(map, true);
    }

    /**
     * Sort the value in the map and swap the pair of view
     * and its rank value in descending order.
     * 
     * @param map the map to be sorted
     * @return the sorted map
     */
    public static <K extends Object, V extends Object> Map<K, V> sortByValue(Map<K, V> map,
            final boolean isDecrease) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Object>() {
            @SuppressWarnings("unchecked")
            public int compare(Object o1, Object o2) {
                int compareValue = ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue())
                        .compareTo(((Map.Entry<K, V>) (o2)).getValue());

                // reverse the order
                if (isDecrease) {
                    if (compareValue == -1)
                        compareValue = 1;
                    else if (compareValue == 1)
                        compareValue = -1;
                } else {
                    if (compareValue == 1)
                        compareValue = 1;
                    else if (compareValue == -1)
                        compareValue = -1;
                }
                return compareValue;
            }
        });

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

Related

  1. sortByValue(Map map)
  2. sortByValue(Map map)
  3. sortByValue(Map map)
  4. sortByValue(Map map)
  5. sortByValue(Map map)
  6. sortByValue(Map map, boolean descending)
  7. sortByValue(Map map, final boolean asc)
  8. sortByValue(Map map)
  9. sortByValue(Map map)