Java 9 — Additional Features (Part-2)

Chinmay Venkata Sabbam
art of coding
Published in
7 min readSep 12, 2020

you need to know about the improvements in java 9 :

In this article we will Focus on the additional features of Java 9

Additional Features in Java 9:

1. Optional (ifPresentOrElse() , stream(),or())

Before discuss about the Additional Features in Optional. First we will try to understand the Optional

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//Statement-1
numbers.stream()
.filter(e-> e> 5)
.findFirst(); // 6
-----------------------------------------------------------------
//Statement-2
numbers.stream()
.filter(e-> e> 50)
.findFirst();// Null

Let’s Imagine if there is No Optional parameter in Java , observe the above code block. if we print the statement-1 it will give the output 6

if we print the statement-2 , it will give Null or Null Pointer Exception. Generally Null is called smell, especially in functional style of coding . So Effectively in Java, we will return empty List. But if we need to return the single element then ????

So In Java 8, Optional parameter is used in functional style of coding to avoid Null pointer Exceptions.

Optional parameter example
output of the above program

if we observe the above program. we did not get the Null Pointer Exceptions. Now Question is
How can we get the parameter from the Optional ???

Let us understand the existed approaches before Java 9. so that we can easily understand the painful point and additional feature in Optional

Note: Don’t try the below program at home or at work place because Optional is the type which is always used at return type but not as Method variable

public static void process(java.util.Optional<Integer> result) {// APPROACH -1         result.get(); 
// dont do this...... get() is to forget because it blows without telling you NoSuchElement Exception
// APPROACH -2 result.orElseThrow();
// it clearly tells you the intension
// APPROACH - 3 result.orElse(0);
// gives value or return 0

// APPROACH -4
result.ifPresent(value -> System.out.println(value));

}
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

java.util.Optional<Integer> op1 = numbers.stream()
.filter(e-> e> 5)
.findFirst();

java.util.Optional<Integer> op2 = numbers.stream()
.filter(e-> e> 50)
.findFirst();
process(op1);
process(op2);
}

Approach-1 | result.get() : Don’t use this method because it blows up with NoSuchElement Exception without any notice, if Optional is empty.

Approach-2 | result.orElseThrow() : it will throw the Exception with intimation , if Optional is empty. it is better than get() method

Approach-3 | result.orElse(value): it will return the value specified, if Optional is empty

Approach-4 | result.ifPresent((logic)) : it will handle the logic , if Optional is not empty

Problem : if we need to handle some logic , if Optional is empty . then ……………

if(!result.isPresent()) {

}

if we handle in the above code mentioned, it will comes under the imperative style of coding and not comes under the functional style of coding

So In Java 9, they introduced the ifPresentOrElse() method

1.1 ifPresentOrElse():

result.ifPresentOrElse(value -> System.out.println(value), ()-> System.out.println("there is no value"));
ifPresentOrElse Method in java 9
output of the above program

Let us Observe the differences between the Optional and the Stream

Optional may have 0 or 1 values . Stream may have 0,1 or more values that means Optional is a subset of Stream. Now the Question arrived
why can’t we use Optional as a Stream ????

So In Java 9, they introduced the stream() method

1.2 stream():

stream() method in java 9
output of the above code

Note : Stream can iterate not only with empty but also with one or more elements

1.3 or():

let us compare or() with orElse() method so that you can clearly understood the difference

Difference between the or and orElse
Comparison Program of or() and orElse() methods
output of the above program

2. Completable Future (completeOnTimeOut(),orTimeOut(),copy())

In Programming we must be careful not only with deadlocks but also with live-locks as well especially when you deal with the Asynchronous Programming.

Completable future consists an asynchronous programming flavor Just like Promises in JavaScript

live lock :
Pseudo code:

public static int factory() {
try {
// if this logic would take 3 hrs time to execute
} catch (InterruptedException e) {
e.printStackTrace();
}
return 42;
}

CompletableFuture.supplyAsync(factory())
.thenAccept(System.out::println);

if we execute this Completable Future, it takes 3hrs to complete. it is called live lock. especially in asynchronous programming it could not work. we need specific amount of timeouts. To Solve this problem, In Java 9 two timeout Methods are introduced in Completable future (completeOnTimeOut() and orTimeOut())

2.1 completeOnTimeOut():

completeOnTimeout(value, time, TimeUnit)

eg. ::: completeOnTimeout(-1, 2, TimeUnit.SECONDS)

if task will complete with in 2 seconds, it would give the result, if it exceeds 2 seconds it returns value -1

2.2 orTimeOut():

orTimeout(time, TimeUnit)

eg ::: orTimeout(2, TimeUnit.SECONDS)

if task will complete with in 2 seconds , it would give the result, if it exceeds timeout the operation

In addition to this Java 9 introduces the copy() method. which is used to copy the entire functional Composition of the completable future without creating the new one again

2.3 copy():

copy(Completable Future)

CompletableFuture<Integer> cp = CompletableFuture.supplyAsync(CompletableFutureWithJava9::factory);
CompletableFuture<Integer> cp2 = cp.copy();
CompleteOnTimeOut,orTimeOut,Copy methods in Completable Futures with Java 9
Output of the above Program

3. Collectors (Filtering and FlatMapping)

we all know that filter() and flatMap() are the functions which are available in the streams. In Java9, they also introduced in the collectors Interface to solve the different use cases with the functional programming

USECASE:

LIST 1 ::: {1, 2, 3, 4, 5, 6}, LIST 2 ::: {7, 8, 9, 10}
I need output Map<Integer,List> = Map<Size of the List,LIST of even Numbers in List> = {{6,{2,4,6}},{4,{8,10}}

it can be easily solve with flatMapping() in collectors which is introduced in Java 9

Solution for above use case is in advanced benefits
Output of the above Program

4. Immutable Collections (of())

Before Discussing about the of() method, first we need to understand about the Arrays.asList(elements) method

Arrays.asList Behaviour observation
output of the above program

By Seeing this above Program, Do you felt Arrays.asList(elements) is a immutable ??????

Lets observe below program

Arrays.aslist (behaviour)
output of the above program

if you observe the output , it clear shows that it mutates the value (1 with 4) and it’s class is ArrayList

of()

Observe the Behaviour of()
Output of the above program

Same program if you run with of(), we are getting the Exception …. why ???

Comparision of Arrays.asList() and List.of()
Output of the above program

Here we can clearly see the difference:

Arrays.asList() is mutable and it is having class name ArrayList and List.of() is immutable and it is having a class Name Immutable Collections

Set<String> set = Set.of("Tom","Jerry","Hello");
Map<String,Integer> map = Map.of("a",1,"b",2,"c",3,"z",5);

In the similar way we have Set.of() and Map.of () which gives you Immutable Collections

Set<String> set = Set.of("Tom","Jerry","Tom");

Note: Above code gives you a RunTimeException, where as HashSet will allow

RUNTIME EXCEPTIONS:
System.out.println(Map.of("a",1,"b",2,"c",3,5,"z"));
System.out.println(Set.of("Tom","Jerry",123));
System.out.println(Map.of("a",1,"b"));
COMPILE TIME EXCEPTIONS :
Map<String,Integer> map = Map.of("a",1,"b",2,"c",3,5,"z");
Set<String> set = Set.of("Tom","Jerry",123);
System.out.println(Set<String>.of("Tom","Jerry",123)); System.out.println(Map<String,Integer>.of("a",1,"b",2,"c",3,5,"z"));

5. Diamond Operator<> Extension for the anonymous classess

In Java 1.7, Diamond Operator <> is applicable only for classess. Now it is Extended to the Anonymous classess

Diamond Operator for the anonymous classes

In the above code commented code is in Java 8 Implementation.

6. Http/2

http2 implementation

In the Upcoming Blog (Part-3) we will concentrate on advanced features of Java 9

  • JShell
  • Modularization (it changes the entire landscape of Java)
  • StackWalker(Processing the stacks traces in to Streams)

Stay Tuned…….

Follow this Publication for timely updates

Medium :

https://medium.com/art-of-coding

Linked in :

https://www.linkedin.com/company/art-of-coding/

--

--