如何对Map<键,值>进行排序Java与谷歌集合排序功能中的值 [英] How to sort a Map<Key, Value> on the values in Java with google collections ordering function

查看:82
本文介绍了如何对Map<键,值>进行排序Java与谷歌集合排序功能中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

以下是使用通用方法的代码段,该方法采用Map<K,V>Comparator<? super V>,并返回其entrySet()排序后的SortedSet使用比较器计算这些值.

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]"
    }
}


在Google订购中

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

返回现有比较器的顺序.

Returns an ordering for a pre-existing comparator.

上述解决方案使用Comparator,因此您可以轻松地使用上述方法来使用Ordering.

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

这篇关于如何对Map&lt;键,值&gt;进行排序Java与谷歌集合排序功能中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆