B が double 型のフィールドを持つクラスの場合、Google コレクションの順序付け関数を使用して Java の値で map(?,B) を並べ替える方法は、順序付けに使用する必要があります。
6716 次
2 に答える
4
Map<K,V>
aと aを受け取り、コンパレータを使用して値でソートされたaをComparator<? super V>
返すジェネリック メソッドを使用するスニペットを次に示します。SortedSet
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]"
}
}
Google での注文
public static <T> Ordering<T> from(Comparator<T> comparator)
既存のコンパレータの順序を返します。
上記のソリューションでは を使用しているComparator
ため、代わりに上記の方法を簡単に使用できますOrdering
。
于 2010-05-22T20:02:02.300 に答える
-3
Collections.sort(map.values(), myComparator); myComparator を Comparator として作成し、B オブジェクトを double フィールドで比較します。
于 2010-05-22T19:51:04.007 に答える