Java Map Sort sortByValue(Map map)

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

Description

sort By Value

License

Open Source License

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Open Source 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;

import java.util.Map.Entry;

public class Main {
    public static <K, V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> map) {
        Comparator<Map.Entry<K, V>> valueComparator = null;

        valueComparator = new Comparator<Map.Entry<K, V>>() {
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }/*from   www .  jav  a  2  s  .  c o  m*/
        };

        final List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());

        Collections.sort(entries, valueComparator);

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

Related

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