Stream API Improvement in Java 9

Last updated on Dec 29 2022
Prabhas Ramanathan

In Java 9, Stream API has improved and new methods are added to the Stream interface. These methods are tabled below.

Modifier and Type Method Description
default Stream<T> takeWhile(Predicate<? super T> predicate) It returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of a subset of elements taken from this stream that match the given predicate.
default Stream<T> dropWhile(Predicate<? super T> predicate) It returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.
static <T> Stream<T> ofNullable(T t) It returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) It returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate. The stream terminates as soon as the hasNext predicate returns false.

Table of Contents

Java Stream takeWhile() Method

Stream 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 1

In this example, we have a list of integers and picks up even values by using takewhile method.

 
1. import java.util.List; 
2. import java.util.stream.Collectors; 
3. import java.util.stream.Stream; 
4. public class StreamExample { 
5. public static void main(String[] args) { 
6. List<Integer> list 
7. = Stream.of(1,2,3,4,5,6,7,8,9,10) 
8. .takeWhile(i -> (i % 2 == 0)).collect(Collectors.toList()); 
9. System.out.println(list); 
10. } 
11. }

This example returns an empty list because it fails at first list element, and takewhile stops here.
Output:
[]

Java Stream takeWhile() Method Example 2

1. <p>In this example, we are getting first two elements because these are even and stops at third element. </p> 
2. <div class="codeblock"><textarea name="code" class="java"> 
3. import java.util.List; 
4. import java.util.stream.Collectors; 
5. import java.util.stream.Stream; 
6. public class StreamExample { 
7. public static void main(String[] args) { 
8. List<Integer> list 
9. = Stream.of(2,2,3,4,5,6,7,8,9,10) 
10. .takeWhile(i -> (i % 2 == 0)).collect(Collectors.toList()); 
11. System.out.println(list); 
12. } 
13. }

Output:
[2,2]

Java Stream dropWhile() Method

Stream 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 Example

1. import java.util.List; 
2. import java.util.stream.Collectors; 
3. import java.util.stream.Stream; 
4. public class StreamExample { 
5. public static void main(String[] args) { 
6. List<Integer> list 
7. = Stream.of(2,2,3,4,5,6,7,8,9,10) 
8. .dropWhile(i -> (i % 2 == 0)).collect(Collectors.toList()); 
9. System.out.println(list); 
10. } 
11. }

Output:
[3, 4, 5, 6, 7, 8, 9, 10]

 

Java 9 Stream ofNullable Method

Stream 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 Example 1

1. import java.util.List; 
2. import java.util.stream.Collectors; 
3. import java.util.stream.Stream; 
4. public class StreamExample { 
5. public static void main(String[] args) { 
6. List<Integer> list 
7. = Stream.of(2,2,3,4,5,6,7,8,9,10) 
8. .dropWhile(i -> (i % 2 == 0)).collect(Collectors.toList()); 
9. System.out.println(list); 
10. } 
11. }

Output:
25

Stream can have null values also.

Java 9 Stream ofNullable Method Example 2

1. import java.util.stream.Stream; 
2. 
3. public class StreamExample { 
4. public static void main(String[] args) { 
5. Stream<Integer> val 
6. = Stream.ofNullable(null); 
7. val.forEach(System.out::println); 
8. } 
9. }

This program will not produce any output.

Java Stream Iterate Method

A 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 Example

1. import java.util.stream.Stream; 
2. 
3. public class StreamExample { 
4. public static void main(String[] args) { 
5. Stream.iterate(1, i -> i <= 10, i -> i*3) 
6. .forEach(System.out::println); 
7. } 
8. }

Output:
1
3
9

Java 9 Underscore

In earlier versions of Java, underscore can be used as identifier and to create variable name also. But in Java 9 release, underscore is a keyword and can’t be used as an identifier or variable name.
If we use the underscore character (“_”) as an identifier, our source code can no longer be compiled.
Let’s see some examples that explain, how the use of underscore is changed version after after.
In Java 7, we can use underscore like the following.

Java 7 Underscore Example

1. public class UnderScoreExample { 
2. public static void main(String[] args) { 
3. int _ = 10; // creating variable 
4. System.out.println(_); 
5. } 
6. }

And it produce the output without any warning and error.
Output:
10

 

Java 8 Underscore Example

If we compile the same program in Java 8, it will compile but throws a warning message.

1. public class UnderScoreExample { 
2. public static void main(String[] args) { 
3. int _ = 10; 
4. System.out.println(_); 
5. } 
6. }

Output:
UnderScoreExample.java:3: warning: ‘_’ used as an identifier
int _ = 10;
^
(use of ‘_’ as an identifier might not be supported in releases after Java SE 8)

 

Java 9 Underscore Example

In Java 9, program fails to compile and throws compile time error because now it is a keyword and can’t be use as a variable name.

1. public class UnderScoreExample { 
2. public static void main(String[] args) { 
3. int _ = 10; 
4. System.out.println(_); 
5. } 
6. }

Output:
UnderScoreExample.java:3: error: as of release 9, ‘_’ is a keyword, and may not be used as an identifier
int _ = 10;

So, this brings us to the end of blog. This Tecklearn ‘Stream API Improvement in Java 9’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Stream API Improvement in Java 9"

Leave a Message

Your email address will not be published. Required fields are marked *