Professional Documents
Culture Documents
Java 8 Features
Java 8 Core Java java by devs5003 - July 10, 2021 2
https://javatechonline.com/java-8-features/ 1/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
Changes in Language :
Lambdas(λ) and Functional Interfaces
Repeating Annotations
Streams
StringJoiner
Base64
Parallel Arrays
Concurrency
1) C#.Net
2) C Objective
3) C
4) C++
https://javatechonline.com/java-8-features/ 2/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
5) Python
6) Ruby etc.
☀ The Main Objective of Lambda Expression is to bring benefits of functional programming in Java.
Lambda Expression is an anonymous (nameless) function. In other words, the function which doesn’t have the name, return
type and access modifiers. Lambda Expression also referred to as anonymous functions or closures.
System.out.println(i+j);
Step#4 : insert arrow sign (→) between remaining method declaration & body ⇒ (int i, int j) →{ System.out.println(i+j); }
Step#5 : If the compiler is able to identify the type of parameters, remove them as well ⇒ (i, j) →{ System.out.println(i+j); }
If the type of the parameter can be decided by the compiler automatically based on the context, then we can remove parameter types
also. Further, the above Lambda expression can be rewritten as (a,b) -> System.out.println (a*b);
Example 3: For example, suppose we have a String, we wanted to do modification on this string & getting String again after multiple
operations. We will write a method as below:
https://javatechonline.com/java-8-features/ 3/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
2. Similar to the method body, lambda expression body can contain multiple statements. If more than one statements present, then we
have to enclose it within curly braces. If one statement present, then curly braces are optional. As in example at point # 1 can again be
simplified as s-> System.out.println(s);
3. However, if no parameters are available, we can use empty parenthesis like : ()->System.out.println(“No parameter test”);
4. Additionally, we can call the Lambda expression just like a traditional method, but only with the help of functional interfaces. We have
covered Functional Interfaces in detail in the separate Topic.
♥ In order to get more details on Lambda Expressions , visit our separate tutorial on Lambda Expressions in Java 8.
Functional Interfaces :
If an interface contains only one abstract method, such type of interface is called functional interface and the contained method is
called functional method or single abstract method (SAM). Functional interfaces provide target types for lambda expressions and
method references. One separate package java.util.Function has been introduced for Functional Interfaces.
Note : In addition to single abstract method, we can have any number of default & static methods and even public methods of
java.lang.Object class inside a Functional Interface.
@FunctionalInterface
Interface FunctionalInterface1 {
//This is not a Functional Interface. This code will show compilation error
@FunctionalInterface
Interface NonFunctionalInterface2 {
♥ In order to get more details on Functional Interfaces, visit our separate tutorial on Functional Interfaces in Java 8.
♥ Additionally, in order to get details on Predefined Functional Interfaces, visit our separate tutorial on Predefined Functional
Interfaces in Java 8.
interface Human {
void speaks();
https://javatechonline.com/java-8-features/ 4/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
p
void eats();
Implementing classes are free to provide their own implementation of the default method. If the implementing class doesn’t override
the default method, it means that the class doesn’t need that functionality in it.
♥ In order to get more details on Default Methods in Interfaces, visit our separate tutorial on Default Methods in Interfaces in Java 8.
The Process of declaring a Static method in Interface is similar to defining a Static method in a class. In simple words, we have to use
the static keyword while defining the method. For example, look at the code below.
interface A {
♥ In order to get more details on Static Methods in Interfaces, visit our separate tutorial on Static Methods in Interfaces in Java 8.
Method References
As we have seen in Lambda expression’s topic that we use lambda expressions to implement Functional interfaces with minimum lines
of code and even to get better code readability. Similarly, we can use Method References(::) Java 8 to implement Functional interfaces
with even lesser code again than lambda expressions and this time we get the benefit of code re-usability as well, because we don’t
provide implementation for functional interface. Instead, we provide reference to already existing method(with similar argument types)
to simplify the implementation of the functional interface using double colon (::) operator. This process of providing reference to pre-
existing method is called Method reference.
♥ In order to get more details on Method References, visit our separate tutorial on Method References in Java 8.
Optional
It is also one of the most interesting feature among all new features in Java 8. Optional is a new class under package java.util. The
purpose of this call is to address the infamous NullPointerException. Many people in the industry believe that you are not a real Java
programmer until you’ve dealt with a NullPointerException. Since NullPointerException indicates the absence of a value, the null
reference is the source of many problems. So, Optional class can address some of these problems.
What can you do to prevent NullPointerException? You will add checks to prevent null dereferences. However, sometimes applying too
many null checks, decreases the readability of our code. Unfortunately, we need a lot of boilerplate code to make sure we don’t get
a NullPointerException. Furthermore, it is an error-prone process; what if you forget to check that one property could be null? Hence,
we need is a better way to model the absence and presence of a value.
Java SE 8 introduces a new class called java.util.Optional<T> that is inspired from the ideas of Haskell and Scala. It is a class that
encapsulates an optional value. In a nutshell, Optional is a single-value container that either contains a value or doesn’t (it is then said
to be “empty”). The Optional class includes methods to explicitly deal with the cases where a value is present or absent.
Creating Optional objects
For example, below code creates an empty Optional.
https://javatechonline.com/java-8-features/ 5/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
Also, by using ofNullable, you can create an Optional object that may hold a null value:
♦ Note: You should only use of() when you are sure the object is not null. If the object can be both null or not-null, then you should
instead choose the ofNullable() method.
Stream
The Stream is also another feature of Java 8. A stream is nothing, but a sequence of objects. It offers us various methods to produce
the desired result in minimum lines of code. Stream takes inputs from Collections, Arrays or I/O channels and provides the result as per
the pipelined methods, but don’t change the original data structure.
Empty Stream
We create an empty Stream with the help of empty() method when we want to avoid returning null for Streams having no element. For
example:
Stream of Array
One of the sources is an Array to create a stream. We call it Stream of Array. Below are the two ways to create an Array of Streams. For
example:
Stream of Collection
Needless to say, we can create stream of any type of Collection like Set, List. For example:
Stream of Primitives
We can create streams of three primitive types such as int, long and double in Java 8. For that, we have three special interfaces :
IntStream, LongStream, DoubleStream to work on int, long and double respectively. We can use two methods to generate any of the
three types of streams of primitives. These are : range(int startInclusive, int endExclusive) and rangeClosed(int startInclusive, int
endInclusive)
https://javatechonline.com/java-8-features/ 6/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
range(int startInclusive, int endExclusive) method creates an ordered stream from the first parameter to the second parameter. It
increments the value of subsequent elements with the step equal to 1. The result doesn’t include the last parameter, it is just an upper
bound of the sequence.
rangeClosed(int startInclusive, int endInclusive) method does the same thing with only one difference, the second element is
included.
For example :
Since Java 8, the Random class provides a wide range of methods for generating streams of primitives. For example, the following code
creates a DoubleStream, which has four elements:
Stream of String
Even we can useString as a source for creating a stream with the help of the chars() method of the String class. Since there is no
interface for CharStream in JDK, we use the IntStream to represent a stream of chars instead. For example:
In order to generate the elements, the generate() method accepts a Supplier<T>. As the resulting stream is infinite, we should define
the desired size, or the generate() method will work until it reaches the memory limit. For example, the code below will create a
sequence of twenty strings with the value “pqr”.
While using this method of creating streams, we should specify the desired type, otherwise the build() method will create an instance
of Stream<Object> by default. For example, the code below will create the Stream<String>.
If you want to create an infinite stream, use iterate() method. For example, the code below will create a Stream of integers starting from
value 24, as the first parameter of the method is 24. The second element in the stream will be 28, as per the expression in the second
parameter of the method.
Stream of a File
When we create a stream of a file containing the text, every line of the text becomes an element of the stream. Furthermore, Java NIO
class Files offers us to generate a Stream<String> of a text file through the lines() method. For example:
https://javatechonline.com/java-8-features/ 7/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
Stream<String> streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
The already existing classes before Java8 (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential
concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code. In
order to address these problems and provide better support in the JDK core, a new date and time API, which is free of these problems,
has been designed for Java SE 8. The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under
JSR 310. Hence, sometimes we also call it Joda API.
Class Purpose
These types can be mapped to vendor-specific database types or ANSI SQL types; for example, the ANSI mapping looks like Table
below.
DATE LocalDate
TIME LocalTime
TIMESTAMP LocalDateTime
StringJoiner
StringJoiner is a new class added in Java 8 under java.util package. In fact, we can use it for joining Strings by making use of a delimiter,
prefix, and suffix. It comes with below two constructors.
StringJoiner(CharSequence delimiter)
https://javatechonline.com/java-8-features/ 8/11
9/22/22, 2:26 PM Java 8 Features | Making Java Easy To Learn
Example Of StringJoiner
For example, below code snippet demonstrates the feature of StingJoiner class.
joiner.add("Core Java")
.add("Spring Boot")
.add("Angular");
System.out.println(joiner.toString());
Output
♦ In order to learn Java 8 New features in detail kindly visit Core Java Section.
Java Interface
July 26, 2022
In "Core Java"
Like
Tagged Date API features of java features of java 8 Functional Interfaces how to use optional in java 8 Interface’s Default and Static Methods java 1.8
features java 1.8 features with examples java 8 examples Java 8 Features java 8 features examples java 8 features interview questions java 8 features stream
java 8 features tutorial java 8 features with example java 8 features with examples java 8 functional programming tutorial java 8 new features java 8 new features
in simple way java 8 new features interview questions java 8 new features list java 8 new features tutorial java 8 new features tutorial with examples Java 8
StringJoiner java 8 tutorial java features java new features java se 8 tutorial java8 java8 features jdk 1.8 features Lambda Expressions learn java 8
Method References new features in java 8 new features in java 8 with examples Optional optional class in java 8 optional in java 8 optional in java 8
example optional keyword in java Streams StringJoiner StringJoiner class in Java 8 what is java 8 What is new in Java 8? what is optional in java 8 what is
stream in java what is the use of optional in java 8 whats new in java 8 when to use optional in java 8
Previous article
How to work with Apache Kafka in Spring Boot?
Next article
How to monitor Spring Boot Microservices using ELK Stack?
Reply
Reply
https://javatechonline.com/java-8-features/ 9/11