2017-02-04 97 views
3

我使用fj.data.List過濾Java的8名單

import fj.data.List 

List<Long> managedCustomers 

我試圖對其進行過濾,使用下面提供的清單類型功能的Java類型列表清單:

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

我得到這個消息

enter image description here

根據文檔,列表H中作爲過濾方法,這應該工作 http://www.functionaljava.org/examples-java8.html

我錯過了什麼?

感謝

+7

列表界面上沒有'filter'方法。如果底層實現允許並且您想要修改「.st​​ream()。filter(...)。collect(toList())」或「managedCustomers.removeIf(id - > id!= 5424164219L)原始列表。 –

回答

3

正如已經@AlexisÇ

在評論中指出的可能值
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請編輯和更新信息的問題,不要只是評論。 – nullpointer

+1

@NirBenYaacov用你的列表類型更新了答案 – nullpointer

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

lambda根據上下文確定它的類型。當你有一個不編譯的語句時,javac有時會變得困惑,並抱怨你的lambda不會編譯,當真正的原因是你犯了一些其他的錯誤,這就是爲什麼它不能解決什麼類型的lambda應該是。

在這種情況下,沒有List.filter(x)方法,這是您應該看到的唯一錯誤,因爲除非您確定您的lambda永遠不會有意義。

在這種情況下,而不是使用過濾器,你可以使用anyMatch因爲你已經知道,只有一個地方customerId == 5424164219L

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