How to sort a Map on the values in Java with

2019-08-14 04:15发布

How to sort a map(?,B) on the values in Java with google collections ordering function, if B is a class, which has a field of type double, which should be used for ordering.

标签: java guava
2条回答
Rolldiameter
2楼-- · 2019-08-14 04:43

Here's a snippet that uses a generic method that takes a Map<K,V> and a Comparator<? super V>, and returns a SortedSet of its entrySet() sorted on the values using the comparator.

public class MapSort {
    static <K,V> SortedSet<Map.Entry<K,V>>
    entriesSortedByValues(Map<K,V> map, final Comparator<? super V> comp) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Entry<K, V> e1, Entry<K, V> e2) {
                    return comp.compare(e1.getValue(), e2.getValue());
                }

            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }
    static class Custom {
        final double d;   Custom(double d) { this.d = d; }
        @Override public String toString() { return String.valueOf(d); }
    }
    public static void main(String[] args) {
        Map<String,Custom> map = new HashMap<String,Custom>();
        map.put("A", new Custom(1));
        map.put("B", new Custom(4));
        map.put("C", new Custom(2));
        map.put("D", new Custom(3));
        System.out.println(
            entriesSortedByValues(map, new Comparator<Custom>() {
                @Override public int compare(Custom c1, Custom c2) {
                    return Double.compare(c1.d, c2.d);
                }           
            })
        ); // prints "[A=1.0, C=2.0, D=3.0, B=4.0]"
    }
}

On Google Ordering

public static <T> Ordering<T> from(Comparator<T> comparator)

Returns an ordering for a pre-existing comparator.

The above solution uses a Comparator, so you can easily use the above method to use Ordering instead.

查看更多
倾城 Initia
3楼-- · 2019-08-14 04:53

Collections.sort(map.values(), myComparator); Create myComparator as Comparator to compare the B objects by the double field.

查看更多
登录 后发表回答