所以我有以下HashMap:
HashMap<String, List<someDataType>> map
;
我想创建一个新的HashMap,它只由k/v对组成,map
其中有一个值(列表),其长度小于某个"x".我知道如何做到这一点的唯一方法是遍历HashMap并将k/v对放入新的HashMap中.有没有更简洁的方法来实现我正在寻找的东西?谢谢.
Kei*_*ith 10
使用番石榴:
Map<String, List<String>> newMap =
Maps.filterEntries(originalMap, new MyEntryPredicate(10));
Run Code Online (Sandbox Code Playgroud)
哪里:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果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);
Run Code Online (Sandbox Code Playgroud)
请注意需要复制,因为它会filterValues
返回原始地图的过滤视图。
更新:使用Java 8,您可以将谓词简化为lambda表达式:
Map<String, List<String>> filteredMap = Maps.filterValues(map, list -> list.size() < x);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5565 次 |
最近记录: |