How to sort a map(?,B) on the val开发者_如何学编程ues 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.
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]"
}
}
On Google Ordering
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.
Collections.sort(map.values(), myComparator); Create myComparator as Comparator to compare the B objects by the double field.
精彩评论