Lets assume i want to iterate over a collection of objects.
List<String> strmap = ...
//Without lambdas
strmap.stream().filter(new Predicate<String>() {
public boolean test(String string) {
return string.length == 10;
}
}.forEach(new Consumer<String>() {
public void accept (String string) {
System.out.println("string " + string + " contains exactly 10 characters");
}
}
//With lambdas
strmap.stream()
.filter(s -> s.length == 10)
.forEach(s -> System.out.println("string " + s + " contains exactly 10 characters");
How does the second example (without lambdas) work? A new object (Predicate and Consumer) created every time i call the code, how much can java jit compiler optimalize a lambda expression? For a better performace should i declare all lambdas as a variable and always only pass a reference?
private Predicate<String> length10 = s -> s.length == 10;
private Consumer<String> printer = s -> { "string " + s + " contains exactly 10 characters"; }
strmap.stream()
.filter(length10)
.forEach(printer);