したがって、次の HashMap があります。
HashMap<String, List<someDataType>> map
;
map
長さが特定の「x」未満の値 (リスト) を持つk/v ペアのみで構成される新しい HashMap を作成したいと考えています。これを行う方法を私が知っている唯一の方法は、HashMap を反復処理し、k/v ペアを新しい HashMap に入れることです。私が探しているものを達成するためのより簡潔な方法はありますか? ありがとう。
グアバの使用:
Map<String, List<String>> newMap =
Maps.filterEntries(originalMap, new MyEntryPredicate(10));
どこ:
private static class MyEntryPredicate implements Predicate<Map.Entry<String, List<String>>> {
// max list length, exclusive
private int maxLength;
private MyEntryPredicate(int maxLength) {
this.maxLength = maxLength;
}
@Override
public boolean apply(Map.Entry<String, List<String>> input) {
return input != null && input.getValue().size() < maxLength;
}
}
Guavaライブラリがプロジェクトで利用できる場合は、次を使用できますMaps.filterValues
(Keith の回答を多少反映しています)。
final int x = 42;
Map<String, List<String>> filteredMap =
Maps.filterValues(map, new Predicate<Collection<?>>() {
@Override
public boolean apply(final Collection<?> collection) {
return collection.size() < x;
}
});
Map<String, List<String>> filteredMapCopy = ImmutableMap.copyOf(filteredMap);
元のマップのフィルター処理されたビューfilterValues
を返すため、コピーが必要であることに注意してください。
更新: Java 8 では、述語をラムダ式に単純化できます。
Map<String, List<String>> filteredMap = Maps.filterValues(map, list -> list.size() < x);
GoogleのGuavaライブラリを参照してください。そこには膨大な数のCollections
関連Map
するユーティリティがあり、複雑なことを非常に簡潔に行うことができます。できることの例は次のとおりです。
Iterable<Long> list =
Iterables.limit(
Iterables.filter(
Ordering.natural()
.reverse()
.onResultOf(new Function<Long, Integer>() {
public Integer apply(Long id) {
return // result of this is for sorting purposes
}
})
.sortedCopy(
Multisets.intersection(set1, set2)),
new Predicate<Long>() {
public boolean apply(Long id) {
return // whether to filter this id
}
}), limit);
私はあなたが探していることを行うことができる何かをそこに見つけることができると確信しています:-)
または、元のマップのコピーを作成し、長さが x 未満の値を削除して値を反復処理することもできます。