gpt4 book ai didi

java - 可以按值的顺序迭代的映射

转载 作者:太空狗 更新时间:2023-10-29 22:45:00 25 4
gpt4 key购买 nike

我需要一个可以按其值的降序进行迭代的 map 。 Apache Commons 或 Guava 等标准库是否提供这种 map ?

最佳答案

我将按如下方式使用 Guava 执行此操作:

Ordering<Map.Entry<Key, Value>> entryOrdering = Ordering.from(valueComparator)
.onResultOf(new Function<Entry<Key, Value>, Value>() {
public Value apply(Entry<Key, Value> entry) {
return entry.getValue();
}
}).reverse();
// Desired entries in desired order. Put them in an ImmutableMap in this order.
ImmutableMap.Builder<Key, Value> builder = ImmutableMap.builder();
for (Entry<Key, Value> entry :
entryOrdering.sortedCopy(map.entrySet())) {
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
// ImmutableMap iterates over the entries in the desired order

关于java - 可以按值的顺序迭代的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8896679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com