Recently I was learning about Java 8 features so I started with a lambda expression, then I came across the Java stream API, now I am trying to wrap my head around the methods in stream API, How they work?
What I understood about lambda expression is if we want to pass the lambda expression to the method then we need to create an interface with the single unimplemented method (Java 8 interface can have default implementation) that matches the signature of a lambda expression. then the method to which the lambda expression is passed can execute the lambda expression by calling the interface method. So I can say that a lambda expression works as an implementation of the interface method.
But when I saw Stream API it has some methods which change the stream, for example below code just print integers by filtering integers which are less than 5.
import java.util.Arrays;
import java.util.List;
public class StreamDemo {
static List<Integer> list= Arrays.asList(new Integer(1), new Integer(2), new Integer(3), new Integer(4), new Integer(5), new Integer(6));
public static void main(String[] ar) {
list.parallelStream()
.filter( x-> x<5)
.forEach(System.out::print);
}
}
But I am not understanding, how filter work as it does not have an implementation, I tried to see the implementation from Intellij which takes me to the Stream interface where the filter is non-implemented method which takes the parameter Predicate reference, but there is no method call of predicate method boolean test(T t); so how come Java evaluate the result, similarly there is method distinct which does not have an implementation but still gives me accurate result.
Thanks in advance.
filterdoes have an implementation, in this case it's provided by theStreaminstance returned byparallelStream(). You can find all implementations of an interface method by clicking the little green down arrow in the margin next to the definition.