Java SortedSet sortedByValues(Map map, final boolean asc)

Here you can find the source of sortedByValues(Map map, final boolean asc)

Description

sort a map by value

License

LGPL

Parameter

Parameter Description
map a parameter

Declaration

public static <K, V extends Comparable<? super V>> SortedSet<Entry<K, V>> sortedByValues(Map<K, V> map,
        final boolean asc) 

Method Source Code

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

import java.util.Comparator;

import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main {
    /**/*from  w ww . j a va 2s. c  o m*/
     * sort a map by value
     * 
     * @param map
     * @return
     */
    public static <K, V extends Comparable<? super V>> SortedSet<Entry<K, V>> sortedByValues(Map<K, V> map,
            final boolean asc) {
        SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
                int compareTo = e1.getValue().compareTo(e2.getValue());
                int direct = 1;
                if (!asc) {
                    direct = -1;
                }
                return compareTo * direct;
            }
        });
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }
}

Related

  1. mapToSortedSet(Map map)
  2. newSortedSet()
  3. setDistance(SortedSet s1, SortedSet s2)
  4. setminus(SortedSet pSet1, SortedSet pSet2)
  5. sorted(Iterable input)
  6. sortedConfigKeys(Iterable> conf)
  7. sortedSet()
  8. splitSorted(String str, String sepStr)
  9. toSortedSet(Comparator comparator, Value... values)