Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Java 9 Streams Enhancements - Gowtham Girithar Srirangasamy
Java 8 introduced Streams, which help developers perform aggregate operations from a sequence of objects. Meanwhile, Java 9 introduced a few more utility methods to make developers' work even easier.
Dropwhile will throw away the elements at the start where the predicate is true. For example, it returns a Stream consisting of the remaining elements of this Stream after dropping the longest prefix of elements that match the given predicate (ordered Stream).In an unordered case, return the subset of elements as per their definition.
Takewhile will stop once it has found an element it fails to match, like a Stream consisting of the longest prefix of elements taken from this Stream that matches the given predicate (ordered Stream).In an unordered case, return the subset of elements as per their definition.
Streams has the iterate method with two arguments: One is the initializer, which is called as a seed, and the other argument is the function to be applied to the previous element to produce the new element. But the drawback of that method is that there is no termination of that loop. Java 9 updated the iterate method, which is similar to what we had earlier for loop-based iterations. This is the replacement of for loops. This also solves the problem that we had in the earlier iterate method.
Java 9 introduced the ofNullable method to return empty Optionals if the value is null. The main intention is to avoid NullPointerExceptions and to avoid having null checks everywhere.
In usecases we are writing the code like below Employee emp= getEmployee(empId);
Stream roles= emp== null? Stream.empty(): emp.roles();
This can be re-written as
Employee emp= getEmployee(empId);