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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:17:23  来源:igfitidea点击:

how can I filter map entries based on set of entries

javamapsetguavapredicate

提问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 mapbased on policyand return the filtered map ?

如何过滤roomPrice map基于中的条目policy并返回过滤后的地图?

filteredMapneeds 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 equalsand hashcodein OccupancyType.
  • Loop through roomPrice's keyset and collect the elements contained in the filter.
  • 重写和实现equals,并hashcodeOccupancyType
  • 循环遍历roomPrice的键集并收集过滤器中包含的元素。

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.

应该做的伎俩。