Java Map Sort sortByValues( Map map)

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

Description

sort By Values

License

Apache License

Declaration

@SuppressWarnings("rawtypes")
    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: Apache 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 {
    @SuppressWarnings("rawtypes")
    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());//from w  ww  .  ja  v  a  2 s  .co m

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

            @SuppressWarnings("unchecked")
            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        //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) {
            //diki mou if
            if (Double.parseDouble(entry.getValue().toString()) != 0.0) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
        }

        return sortedMap;
    }
}

Related

  1. sortByValue(Map map)
  2. sortByValue(Map map)
  3. sortByValueAscending(Map map)
  4. sortByValueDESC(Map map)
  5. sortByValueDescending( Map map)
  6. sortByValues(final Map map)
  7. sortByValues(Map map, final Comparator comp)
  8. sortByValues(Map map)
  9. sortByValues(Map map)