Java 9 Stream API ImprovementIn Java 9, Stream API has improved and new methods are added to the Stream interface. These methods are tabled below.
Java Stream takeWhile() MethodStream takeWhile method takes each element that matches its predicate. It stops when it get unmatched element. It returns a subset of elements that contains all matched elements, other part of stream is discarded. Java Stream takeWhile() Method Example 1In this example, we have a list of integers and picks up even values by using takewhile method. This example returns an empty list because it fails at first list element, and takewhile stops here. Output: [] Java Stream takeWhile() Method Example 2Output: [2,2] Java Stream dropWhile() MethodStream dropWhile method returns result on the basis of order of stream elements. Ordered stream: It returns a stream that contains elements after dropping the elements that match the given predicate. Unordered stream: It returns a stream that contains remaining elements of this stream after dropping a subset of elements that match the given predicate. Java Stream dropWhile() Method ExampleOutput: [3, 4, 5, 6, 7, 8, 9, 10] Java 9 Stream ofNullable MethodStream ofNullable method returns a sequential stream that contains a single element, if non-null. Otherwise, it returns an empty stream. It helps to handle null stream and NullPointerException. Java 9 Stream ofNullable Method ExampleThis program will not produce any output. Java Stream Iterate MethodA new overloaded method iterate is added to the Java 9 stream interface. This method allows us to iterate stream elements till the specified condition. It takes three arguments, seed, hasNext and next. Java Stream Iterate Method ExampleOutput: 1 3 9 Next TopicUnderscore Keywords |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India