首先尝试lambda

时间:2014-10-10 12:34:39

标签: java lambda java-8

我试图制作我的第一个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"));

2 个答案:

答案 0 :(得分:2)

您没有在项目中使用Java 8。它在Java 8中编译得很好。但是你在这一行中有一个错误:

return (String[]) filteredNames.toArray();

如果要返回数组,请将return语句更改为此。

return filteredNames.toArray(new String[filteredNames.size()]);

答案 1 :(得分:2)

此代码在使用Java 8编译时有效。请注意,所有错误都与Java 8功能无关:

public class Lambda {

    public static void main(String[] args) {
        final String[] names = {"Wim", "Kian", "Dirk", "Emmanuel", "Frank", "Michael", "Anna", "Damien", "Alberto"};
        final String[] filteredNames = getNamesWithCriteria(names, (String s) -> s.startsWith("A"));

    }

    // changed method to be static
    private static 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);
            }
        }
        // proper conversion to String[]
        return  filteredNames.toArray(new String[filteredNames.size()]);
    }


}