Java 8 列表过滤

4

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

import fj.data.List

List<Long> managedCustomers

我正在尝试使用以下方式进行过滤:

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

我收到了这条信息

enter image description here

根据文档,List有一个过滤方法,应该可以运行http://www.functionaljava.org/examples-java8.html 我错过了什么?
谢谢

7
列表接口上没有filter方法。可以尝试使用.stream().filter(...).collect(toList()),或者如果底层实现允许且想要修改原始列表,则使用managedCustomers.removeIf(id -> id != 5424164219L) - Alexis C.
3个回答

5

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

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

如果customerId等于5424164219L,则应该得到筛选过的列表。
编辑 - 上面的代码修改了现有的managedCustomers并删除了其他条目。另外一种方法是使用stream().filter()函数 -
managedCustomers.stream().filter(mc -> mc == 5424164219L).forEach(//do some action thee after);

编辑2 -

对于特定的fj.List,您可以使用 -

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

1
@NirBenYaacov 请编辑并更新问题的信息,不要只是评论。 - Naman
1
@NirBenYaacov更新了答案,包括您的列表类型。 - Naman

4

您所做的事情似乎有些奇怪,Streams(使用filter)通常是这样使用的(我不知道您真正想做什么,您可以在评论中告诉我以获得更精确的答案):

//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());

1
一个 lambda 表达式的类型由上下文决定。当你有一个无法编译的语句时,javac 有时会感到困惑,并抱怨你的 lambda 无法编译,而真正的原因是你犯了其他错误,这就是为什么它无法弄清楚 lambda 的类型应该是什么。

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

在这种情况下,你可以使用 anyMatch,因为你已经知道只有一个可能的值,其中 customerId == 5424164219L

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接