私は Guava ライブラリを初めて使用し、そのクラスのいくつかを使用してコードを簡素化しようとしています。Map を値でソートする必要がありました。クイック検索で、次のコード スニペットとして受け入れられた回答を投稿するこの投稿が見つかりました。
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
誰かがこれがどのように機能するかを明確にしてもらえますか? 私は何かを理解できていません。
注文の定義は ですOrdering<T>。この場合<T>は になりますMap.Entry。さらに、 のメソッド シグネチャonResultOfはonResultOf(Function<F,? extends T> function).
上記のコードでonResultOfは、次のパラメーターを使用して呼び出されています。
onResultOf(new Function<Entry<Key, Value>, Value>())
この場合、次のことを意味します。
<F> = Entry<Key, Value>
<? extends T> = Value
これは、それValueが a を拡張する型であることを意味しMap.Entryます。
そんなことがあるものか?エントリ マップに Key、Value が含まれている場合、どのようValueに拡張するタイプになることができますか?Map.Entry
私は何かを誤解または誤解していると確信していますが、誰かがこれに光を当てることができれば、グアバと Ordering() クラスをもう少しよく理解するのに役立つことを願っています. 特に仕組みonResultOf(Function)。