Java Map Sort sortByValue(Map map)

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

Description

sort a map by value descending

License

Apache License

Parameter

Parameter Description
map a parameter
totalScore a parameter
tripleCounter a parameter

Declaration

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map<String, Long> sortByValue(Map map) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Collections;
import java.util.Comparator;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main {
    /**//from   w w  w  . ja  v  a  2 s.  c o m
     * sort a map by value descending
     * 
     * @param map
     * @param totalScore
     * @param tripleCounter
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, Long> sortByValue(Map map) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(Object o2, Object o1) {
                return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry<String, Long> entry = (Map.Entry) it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map sortByValue(Map map, Long cutOff) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry<String, Long> entry = (Map.Entry) it.next();
            if (entry.getValue() >= cutOff)
                result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

Related

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