我試圖做出我的第一個lambda示例,但是我無法得到這個簡單的代碼來工作。首先嚐試lambda
import java.util.ArrayList;
import java.util.function.Predicate;
public class Lambda {
public static void main(String[] args) {
final String[] names = {"Wim", "Kian", "Dirk", "Emmanuel", "Frank", "Michaël", "Anna", "Damien", "Alberto"};
final String[] filteredNames = getNamesWithCriteria(names, (String s) -> s.startsWith("A"));
}
private String[] getNamesWithCriteria(final String[] names, Predicate<String> predicate) {
final ArrayList<String> filteredNames = new ArrayList<>();
for(String name : names) {
if(predicate.test(name)) {
filteredNames.add(name);
}
}
return (String[]) filteredNames.toArray();
}
}
這是我得到的錯誤:
Lambda.java:8: error: ')' expected
final String[] filteredNames = getNamesWithCriteria(names, (String s) ->
s.startsWith("A"));
^
Lambda.java:8: error: illegal start of expression
final String[] filteredNames = getNamesWithCriteria(names, (String s) ->
s.startsWith("A"));
^
Lambda.java:8: error: ';' expected
final String[] filteredNames = getNamesWithCriteria(names, (String s) ->
s.startsWith("A"));
一個你確定你編譯代碼Java中8? – Eran 2014-10-10 12:37:09
您可能正在運行JDK 8,但我敢打賭,源代碼級別是在8之前設置的。設置'javac -source 1.8 -target 1.8'。它現在期待一個強制轉換'(String)'的結束。 – 2014-10-10 12:40:08
除了你不可能在Java 8中編譯你的代碼,你還從靜態上下文中調用了非靜態方法getNamesWithCriteria。 – 2014-10-10 12:41:48