Java Map,使用值属性过滤 [英] Java Map, filter with values properties
本文介绍了Java Map,使用值属性过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个
TreeMap resMap new TreeMap<String, Map<String, String>>();
我想过滤并只保留值包含已知对的条目,比如说 ('mike' => 'jordan'),并避免像下面这样的循环
I would like to filter and keep only entries that values contains a known pair, let's say ('mike' => 'jordan'), and avoid a loop like below
在我包含的库 apache.commons 和 google.common 中是否有过滤器方法(这也可能会执行循环,但至少它不那么冗长
Is there in my included libraries apache.commons and google.common a filter method (that probably would do a loop too, but at least it's less verbose
for (Entry<String, TreeMap<String, String>> el : resMap.entrySet()){
if (el.getValue().get("mike").equals("jordan")){
//
}
}
推荐答案
您可以使用来自 Guava 的过滤器和 Predicate
接口.
You can use filters from Guava and the Predicate
interface.
Predicate<T> yourFilter = new Predicate<T>() {
public boolean apply(T o) {
// your filter
}
};
所以,简单的例子是:
Predicate<Integer> evenFilter = new Predicate<Integer>() {
public boolean apply(Integer i) {
return (i % 2 == 0);
}
};
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Map<Integer, Integer> evenMap = Maps.filterValues(map, evenFilter);
这篇关于Java Map,使用值属性过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文