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();
精彩评论