【问题标题】:Filtering on Java 8 List过滤 Java 8 列表
【发布时间】:2017-06-21 17:53:37
【问题描述】:

我有一个使用 fj.data.List 提供的 List 类型的函数式 Java 中的 List 类型列表

import fj.data.List

List<Long> managedCustomers

我正在尝试使用以下方法对其进行过滤:

managedCustomers.filter(customerId -> customerId == 5424164219L)

我收到这条消息

根据文档,List 有一个过滤器方法,这应该可以工作 http://www.functionaljava.org/examples-java8.html

我错过了什么?

谢谢

【问题讨论】:

  • 列表界面没有filter方法。如果底层实现允许并且您想修改原始列表,请尝试.stream().filter(...).collect(toList())managedCustomers.removeIf(id -&gt; id != 5424164219L)

标签: java functional-programming java-8 functional-java


【解决方案1】:

正如@Alexis C 的评论中已经指出的那样

managedCustomers.removeIf(customerId -> customerId != 5424164219L);

如果customerId 等于5424164219L,则应该为您提供过滤列表。


编辑 - 上面的代码修改了现有的managedCustomers 删除了其他条目。另一种方法是使用stream().filter() as -

managedCustomers.stream().filter(mc -> mc == 5424164219L).forEach(//do some action thee after);

编辑 2 -

对于具体的fj.List,可以使用-

managedCustomers.toStream().filter(mc -> mc == 5424164219L).forEach(// your action);

【讨论】:

  • @NirBenYaacov 请用信息编辑和更新问题,不要只是评论。
  • @NirBenYaacov 用您的列表类型更新了答案
【解决方案2】:

你做的好像有点奇怪,Streams(使用filter)常用这样的(不知道你真的想对过滤列表做什么,你可以在评论中告诉我tp得到更准确的答案):

//Select and print
managedCustomers.stream().filter(customerId -> customerId == 5424164219L)
                         .forEach(System.out::println);

//Select and keep
ArrayList<> newList = managedCustomers.stream().filter(customerId -> customerId == 5424164219L)
                         .collect(Collectors.toList());

【讨论】:

    【解决方案3】:

    lambda 根据上下文确定它的类型。当您有一个无法编译的语句时,javac 有时会感到困惑并抱怨您的 lambda 无法编译,而真正的原因是您犯了其他错误,这就是为什么它无法锻炼您的类型lambda 应该是。

    在这种情况下,没有 List.filter(x) 方法,这是您应该看到的唯一错误,因为除非您修复您的 lambda 永远不会有意义。

    在这种情况下,您可以使用 anyMatch 而不是使用过滤器,因为您已经知道只有一个可能的值是 customerId == 5424164219L

    if (managedCustomers.stream().anyMatch(c -> c == 5424164219L) {
        // customerId 5424164219L found
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 2021-07-01
      • 2015-10-23
      • 2021-12-20
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多