This question already has an answer here:
- Do Java Lambda Expressions Utilize “Hidden” or Local Package Imports? 4 answers
The question I have involves both Lambdas and Streams. There are a couple of things that I can't resolve. Starting with the lambdas, using Predicate as the example.
Notice how in the following code I neither import "java.util.function.Predicate
" nor do I implement the Predicate interface in the class declaration. And yet, the Lambda works just fine. Why is that?
public class Using_Predicate {
public static List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
public static void main(String[] args) {
// passing the numbers List and different Lambdas to the intermediate
// function.
System.out.println();
printVals(numbers, x -> x > 6); // all values greater than 6
System.out.println();
printVals(numbers, x -> x % 2 == 0); // all even values
System.out.println();
printVals(numbers, x -> x < 8); // ll values less than 8
System.out.println();
printVals(numbers, x -> x % 2 == 1); // all odd values
}
//intermediate Predicate function
public static void printVals(List<Integer> val, Predicate<Integer>
condition) {
for (Integer v : val) {
if (condition.test(v)) // if true, print v
System.out.print(v + " ");
}
}
}
Notice how I have to employ an "intermediate function" that utilizes the "test()" method of the Predicate functional interface. However, if I decide to do something similar in using a stream, I again neither have to import java.util.function.Predicate, or java.util.Stream, or implement the Predicate interface in the class declaration. Furthermore, I can use a Predicate Lambda in the stream without even having to create an intermediate function! Why is that?
For example:
// a predicate lambda that prints the first value greater than 3, in this case 5
public class Sample1 {
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 2, 3, 5, 4, 6, 7, 8, 9, 10);
System.out.println(
values.stream()
.filter(e -> e > 3)
.findFirst()
);
}
}
So, I am really confused on the "why" of the rules for Lambdas and streams, but not so much on the "how".