【问题标题】:Are Iterables.filter and Collections2.filter lazy executed?Iterables.filter 和 Collections2.filter 是否延迟执行?
【发布时间】:2015-01-15 11:53:07
【问题描述】:

我尝试过滤AddReport类型的所有元素

但是在 Predicate 主体中放置断点时,我看到那里的代码没有执行。

懒惰吗?我看到各种子类。

不仅仅是AddReport

    Iterable<BaseClass> filtered =
            Iterables.filter(myList,
                    new Predicate<BaseClass>() {
                        @Override
                        public boolean apply(@Nullable BaseClass input) {
                            AddReport addReport = (AddReport) input;
                            return ((addReport != null) && addReport.description.equals(messageBody));
                        }
                    });

    Collection<BaseClass> filtered2
            = Collections2.filter(myList,
            new Predicate<BaseClass>() {
                @Override
                public boolean apply(@Nullable BaseClass input) {
                    AddReport addReport = (AddReport) input;
                    return ((addReport != null) && addReport.description.equals(messageBody));
                }
            });

【问题讨论】:

  • “为什么 [...] 过滤不起作用?”什么告诉你它不起作用?您是否至少尝试过使用生成的IterableCollection?很可能评估确实是懒惰的。但是“番石榴”和“不起作用”是矛盾的。
  • 我写道:“我看到了各种各样的子类。”
  • 是的,operations in Iterables are lazy“除非另有说明,否则此类中生成的所有可迭代对象都是惰性的,这意味着它们的迭代器仅在绝对必要时才会推进支持迭代。”我>; FunctionalExplained wiki 页面:“所有 Guava 过滤器方法都返回视图。” 将结果的元素复制到某个列表或执行简单的 for-each 循环并打印它们以查看计算结果。
  • 我不清楚你在问什么。 “我看到各种子类”是什么意思?

标签: java collections filter guava


【解决方案1】:

在我看来,您可能想要先将您的可迭代对象过滤为仅AddReport 的实例,您可以这样做:

Iterable<AddReport> addReports = Iterables.filter(myList, AddReport.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    相关资源
    最近更新 更多