开发者

google collections ordering on map values

I would like to order a map(A,Double) based on the values.

Function<Map.Entry<A, Double>, Double> getSimFunction = new Function<Map.Entry<A, Double>, Double>() {
        public Double apply(Map.Entry<A, Double> entry) {
            return entry.getValue();
        }
    };

    final Ordering<Map.Entry<A, Double>> entryOrdering = Ordering.natural().onResultOf(getSimFunction);
    ImmutableSor开发者_Python百科tedMap.orderedBy(entryOrdering).putAll(....).build();

How can I create a new sortedMap based on the ordering results or a sortedset based on the map.keyset()?


How about this?

ImmutableMap.Builder<A, Double> builder = ImmutableMap.builder();
for (Map.Entry<A, Double> entry : entryOrdering.sortedCopy(unsortedMap.entrySet())) {
    builder.put(entry.getKey(), entry.getValue());
}
ImmutableMap<A,Double> sortedMap = builder.build();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜