Java Map Sort sortByValues(Map map)

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

Description

sort By Values

License

Open Source License

Declaration

public static <T, R> Map<T, R> sortByValues(Map<T, R> map) 

Method Source Code

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

import java.util.*;

public class Main {
    public static <T, R> Map<T, R> sortByValues(Map<T, R> map) {
        List list = new LinkedList<>(map.entrySet());
        // Defined Custom Comparator here
        Collections.sort(list, Map.Entry.comparingByValue().reversed());

        // Here I am copying the sorted list in HashMap
        // using LinkedHashMap to preserve the insertion order
        HashMap<T, R> sortedHashMap = new LinkedHashMap<>();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry<T, R> entry = (Map.Entry<T, R>) it.next();
            sortedHashMap.put(entry.getKey(), entry.getValue());
        }/* w  ww .  j  a v  a 2  s  .  co m*/
        return sortedHashMap;
    }
}

Related

  1. sortByValues(final Map map)
  2. sortByValues(Map map, final Comparator comp)
  3. sortByValues(Map map)
  4. sortByValues(Map map)
  5. sortByValues(Map map)
  6. sortByValuesDesc(final Map map)
  7. sortClustersKeys(final Map> clusters)
  8. sortDoubleMap(Map map)
  9. sortedByRankThenLength(Map map)