Java Map Sort sortByValue(final Map map)

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

Description

sort By Value

License

Open Source License

Declaration

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(final Map<K, V> map) 

Method Source Code

//package com.java2s;
/**/*w w w  . j  a v a  2  s . c o  m*/
 * Copyright? 2014-2016 LIST (Luxembourg Institute of Science and Technology), all right reserved.
 * Authorship : Olivier PARISOT, Yoanne DIDRY
 * Licensed under GNU General Public License version 3
 */

import java.util.*;

public class Main {
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(final Map<K, V> map) {
        return sortByValue(map, true);
    }

    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(final Map<K, V> map,
            final boolean asc) {
        final 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(final Map.Entry<K, V> o1, final Map.Entry<K, V> o2) {
                final int v = (o1.getValue()).compareTo(o2.getValue());
                if (asc)
                    return v;
                else
                    return -v;
            }
        });

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

Related

  1. sortByValue( final Map map)
  2. sortByValue( Map map)
  3. sortByValue( Map map, final boolean ascendingValues)
  4. sortByValue(final Map m)
  5. sortByValue(final Map map)
  6. sortByValue(final Map map, final boolean asc)
  7. sortByValue(Map map)
  8. sortByValue(Map map)
  9. sortByValue(Map map, Comparator aComp)