4

我使用 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

我错过了什么?

谢谢

4

3 回答 3

5

正如@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);
于 2017-02-04T11:56:05.317 回答
4

你所做的看起来有点奇怪,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());
于 2017-02-04T11:45:10.787 回答
1

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

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

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

if (managedCustomers.stream().anyMatch(c -> c == 5424164219L) {
    // customerId 5424164219L found
}
于 2017-02-04T11:56:01.630 回答