Reputation: 1629
I tried to make my first lambda example but I can't get this simple code to work.
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();
}
}
These are the errors that I get:
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"));
Upvotes: 0
Views: 120
Reputation: 393791
Here's code that works when compiled with Java 8. Note that all your errors are not related to Java 8 features :
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()]);
}
}
Upvotes: 2
Reputation: 1723
You are not using Java 8 in your project. It compiled fine here in Java 8. However you have a bug in this line:
return (String[]) filteredNames.toArray();
If you wanted to return an array, change the return statement to this.
return filteredNames.toArray(new String[filteredNames.size()]);
Upvotes: 2