InterviewSolution
| 1. |
Stream API improvements in Java 9 |
|
Answer» When Java 9 burst onto the scene, it BROUGHT with it some improvements in STREAM API. Quite a few methods were added to the Stream Interface. Let us have a look at some of them.
takewhile() method accepts all VALUES until the predicate RETURNS false. If a stream is ordered, takewhile() returns a stream consisting the longest prefix of elements taken from this stream that match the predicate. If the stream is unordered, the method returns a stream consisting of a subset of elements extracted from this stream that match the given predicate. The syntax: default Stream<T> takeWhile(Predicate<? super T> predicate)Let us see an example of the takeWhile() method: import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.of("y","a","m","","u","f").takeWhile(o->!o.isEmpty()).forEach(System.out::print); } }The takeWhile() method accepts all y, a, and m and then once it finds the String to be empty, it stops its execution. The output is as follows: $javac Example.java $java Example yam
The dropWhile() method drops all the value until it matches with the predicate. After that, it starts to accept values. The dropWhile() method returns the remaining stream after matching the predicate if the stream is ordered. When the stream is unordered , it returns a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate. The syntax: default Stream <T> dropWhile(Predicate<? super T> predicate)Let us see a program showing the use of the dropWhile() method: import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.of("y","a","m","","u","f").dropWhile(o->!o.isEmpty()).forEach(System.out::print); Stream.of("y","","m","","u","f").dropWhile(o->!o.isEmpty()).forEach(System.out::print); } }dropWhile() method for the first SEQUENCE drops y,a,m values, then once string is empty, it takes all the values. dropWhile() method for the first sequence drops y values, then once string is empty, it takes all the values. $javac Example.java $java Example uf muf
The iterate() method has hasNext predicate as argument which terminates the loop once hasNext predicate returns false. It takes three arguments, seed, hasNext and next. The syntax: static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext,UnaryOperator<T>next)Let us see an example of the iterator method: import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.iterate(1, i -> i <= 10, i -> i*2).forEach(System.out::println); } }The output is as follows: $javac Example.java $java Example 1 2 4 8 10
The ofNullable prevents Null pointer exceptions and prevents null checks for streams. It returns a sequential stream that contains a single element, if non-null. Otherwise, it returns an empty stream. The syntax: static <T> Stream<T> ofNullable(T t) |
|