java 如何根据条目集过滤地图条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11221395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I filter map entries based on set of entries
提问by brainydexter
I'm using google guava 12 and have a map:
我正在使用 google guava 12 并有一张地图:
Map<OccupancyType, BigDecimal> roomPrice;
I have a Set:
我有一套:
Set<OccupancyType> policy;
How can I filter entries in the roomPrice map
based on policy
and return the filtered map ?
如何过滤roomPrice map
基于中的条目policy
并返回过滤后的地图?
filteredMap
needs to have all the values from policy
. In case, roomPrice map doesnt have an entry from policy, I'd like to input default value instead.
filteredMap
需要拥有policy
. 如果 roomPrice 地图没有来自政策的条目,我想输入默认值。
回答by Francisco Paulo
Since you have a Set of keys you should use Maps.filterkeys(), also Guava provides a pretty good set of predicates that you can use out of the box. In your case something like Predicates.in()should work.
由于您有一组键,您应该使用Maps.filterkeys(),Guava 还提供了一组非常好的谓词,您可以开箱即用。在你的情况下像Predicates.in()应该工作。
So basically you end up with:
所以基本上你最终得到:
Map<OccupancyType, BigDecimal> filteredMap
= Maps.filterKeys(roomPrice, Predicates.in(policy));
Hope it helps.
希望能帮助到你。
回答by Jeshurun
- Override and implement
equals
andhashcode
inOccupancyType
. - Loop through
roomPrice
's keyset and collect the elements contained in the filter.
Something like this:
像这样的东西:
Map<OccupancyType, BigDecimal> filteredPrices = new HashMap<OccupancyType, BigDecimal>();
for(OccupancyType key : roomPrice.keySet()) {
if(policy.contains(key) {
filteredPrices.put(key, roomPrice.get(key));
}
}
Update
更新
Ok after reading up a bit on Google Guava, you should be able to do something like:
好吧,在谷歌番石榴上读了一点之后,你应该能够做这样的事情:
Predicate<OccupancyType> priceFilter = new Predicate<OccupancyType>() {
public boolean apply(OccupancyType i) {
return policy.contains(i);
}
};
and then
接着
return Maps.filterValues(roomPrice, priceFlter);
should do the trick.
应该做的伎俩。