简体   繁体   English

如何分类地图 <Key, Value> Java与谷歌集合排序功能中的值

[英]How to sort a Map<Key, Value> on the values in Java with google collections ordering function

如果B是一个类,且其字段类型为double,则应使用google collections排序函数对Java中的值对map(?,B)进行排序。

Here's a snippet that uses a generic method that takes a Map<K,V> and a Comparator<? super V> 这是一个使用通用方法的代码片段,该方法采用Map<K,V>Comparator<? super V> Comparator<? super V> , and returns a SortedSet of its entrySet() sorted on the values using the comparator. Comparator<? super V> ,并使用比较器返回按值排序的entrySet()SortedSet

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 在Google订购中

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. 上面的解决方案使用Comparator ,因此您可以轻松地使用上面的方法来代替Ordering

Collections.sort(map.values(), myComparator); Collections.sort(map.values(),myComparator); Create myComparator as Comparator to compare the B objects by the double field. 创建myComparator作为Comparator,以按double字段比较B对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM