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 <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(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 extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map) {

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

        Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {

            @Override//from  ww  w. j a  v  a2s.  c o  m
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {

                float val1 = Float.parseFloat(o1.getValue().toString());
                float val2 = Float.parseFloat(o2.getValue().toString());

                if (val1 > val2)
                    return -1;
                else if (val1 < val2)
                    return 1;
                else
                    return 0;

            }
        });

        //LinkedHashMap will keep the keys in the order they are inserted
        //which is currently sorted on natural ordering
        Map<K, V> sortedMap = new LinkedHashMap<K, V>();

        for (Map.Entry<K, V> entry : entries) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }
}

Related

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