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<? super V>> Map<K, V> sortByValue(Map<K, V> map) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        List<Map.Entry<K, V>> entriesInList = extractEntriesSortedByValue(map);

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : entriesInList) {
            result.put(entry.getKey(), entry.getValue());
        }/*w  w w. j  av a2  s . c o  m*/
        return result;
    }

    public static <K, V extends Comparable<? super V>> List<Map.Entry<K, V>> extractEntriesSortedByValue(
            Map<K, V> map) {
        List<Map.Entry<K, V>> entriesInList = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(entriesInList, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });
        return entriesInList;
    }
}

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)
  7. sortByValue(Map map, boolean descending)
  8. sortByValue(Map map, final boolean asc)
  9. sortByValue(Map map)