【问题标题】:Why there is no filterValues() method for ListMultiMaps in Guava?为什么 Guava 中的 ListMultiMaps 没有 filterValues() 方法?
【发布时间】:2021-05-31 21:29:16
【问题描述】:

我面临的实际问题是根据任意/灵活的Predicate<V> 过滤ListMultimap<K, V> 的值。

Predicate<Integer> filterCondition = i -> i > 42;
ListMultimap<String, Integer> myMap = MultimapBuilder.hashKeys().arrayListValues().build();
// populate myMap ...

// below does not work 
myMap = Multimaps.filterValues(myMap, filterCondition);

最后一行不起作用,因为 Guava 没有在这里有用的 &lt;K, V&gt; ListMultimap&lt;K, V&gt; filterValues(ListMultimap&lt;K, V&gt; unfiltered, final Predicate&lt;? super V&gt; valuePredicate),即使它两者都有

  • public static &lt;K,V&gt; Multimap&lt;K,V&gt; filterValues(Multimap&lt;K,V&gt; unfiltered, Predicate&lt;? super V&gt; valuePredicate)
  • public static &lt;K,V&gt; SetMultimap&lt;K,V&gt; filterValues(SetMultimap&lt;K,V&gt; unfiltered, Predicate&lt;? super V&gt; valuePredicate)

为什么省略了?

我最终得到了以下解决方法,但这似乎不必要地复杂(并且可能效率低下)。

ListMultimap<String, Integer> myNewMap = MultimapBuilder.hashKeys().arrayListValues().build();
myMap.entries().stream().filter(e -> filterCondition.test(e.getValue()))
    .forEach(e -> myNewMap.put(e.getKey(), e.getValue()));
myMap = myNewMap;

【问题讨论】:

    标签: java guava multimap


    【解决方案1】:

    myMap.get(index) 需要线性时间来执行,但通常 List 实现提供恒定时间get。这和we don't offer Lists.filter的原因是一样的。

    现在确实,get 仅在恒定时间内执行通常。值得注意的是,LinkedList.get takes linear time。但是LinkedList 本身对于大多数用例来说都是错误的选择,所以我们通常不想遵循它的先例。

    除此之外,我们有点遗憾所有我们懒惰计算的“视图”集合——所有我们的集合过滤和转换。所以这就是不提供更多此类 API 的更多理由。 We recommend filtering or transforming eagerly, as the JDK does with its Stream API.

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 2012-01-17
      • 2011-04-13
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 2016-10-20
      相关资源
      最近更新 更多