如何根据条目集过滤地图条目

时间:2012-06-27 07:33:46

标签: java map set guava predicate

我正在使用谷歌番石榴12并有一张地图:

Map<OccupancyType, BigDecimal> roomPrice;

我有一套:

Set<OccupancyType> policy;

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

filteredMap需要拥有policy的所有值。如果roomPrice地图没有来自政策的条目,我想改为输入默认值。

3 个答案:

答案 0 :(得分:28)

由于你有一组键,你应该使用Maps.filterkeys(),Guava也提供了一组非常好的谓词,你可以开箱即用。在你的情况下,像Predicates.in()这样的东西应该有效。

所以基本上你最终得到:

Map<OccupancyType, BigDecimal> filteredMap
    = Maps.filterKeys(roomPrice, Predicates.in(policy));

希望它有所帮助。

答案 1 :(得分:2)

  • 覆盖并实施equalshashcode OccupancyType
  • 循环访问roomPrice的密钥集并收集 过滤器中包含的元素。

这样的事情:

Map<OccupancyType, BigDecimal> filteredPrices = new HashMap<OccupancyType, BigDecimal>();
for(OccupancyType key : roomPrice.keySet()) {
    if(policy.contains(key) {
        filteredPrices.put(key, roomPrice.get(key));
    }
}

<强>更新

在谷歌番石榴上读了一下之后,你应该能够做到这样的事情:

Predicate<OccupancyType> priceFilter = new Predicate<OccupancyType>() {
    public boolean apply(OccupancyType i) {
        return policy.contains(i);
    }
};

然后

return Maps.filterValues(roomPrice, priceFlter);

应该这样做。

答案 2 :(得分:0)

无需使用 Guava,Maps.filterKeys() 也会为大型地图产生性能很差的结果。

// (new map can be initialized to better value to avoid resizing)
Map<OccupancyType, BigDecimal> filteredMap = new HashMap<>(roomPrice.size());
for (OccupancyType key: policy) {
    // contains() and get() can usually be combined
    if (roomPrice.contains(key)) {
       filteredMap.put(key, roomPrice.get(key));
    }
}