如果 B 是一个类,它有一个 double 类型的字段,应该用于排序,如何使用谷歌集合排序函数对 Java 中的值进行排序。
问问题
6716 次
2 回答
4
这是一个使用通用方法的片段,该方法采用 aMap<K,V>
和 a Comparator<? super V>
,并使用比较器返回按值排序的SortedSet
a 。entrySet()
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]"
}
}
在谷歌订购
public static <T> Ordering<T> from(Comparator<T> comparator)
返回预先存在的比较器的排序。
上述解决方案使用 a Comparator
,因此您可以轻松地使用上述方法来Ordering
代替。
于 2010-05-22T20:02:02.300 回答
-3
Collections.sort(map.values(), myComparator); 创建 myComparator 作为 Comparator 以通过双字段比较 B 对象。
于 2010-05-22T19:51:04.007 回答