JAVA8 Features
Java8 Features
1) Lambda Expressions: Concise functional code using ->.
Lambda Expression basically expresses an instance of the functional interface,
Lambda Expression provides a clear and concise way to represent a method of the functional interface using an expression.
An interface that contains only one abstract method is known as a functional interface.
There is no restriction, that can have n number of default and static methods inside a functional interface.
A functional interface is an interface that contains only one abstract method.
@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method.
Runnable, ActionListener, and Comparable are some of the examples of functional interfaces.
Runnable –> This interface only contains the run() method.
Comparable –> This interface only contains the compareTo() method.
ActionListener –> This interface only contains the actionPerformed() method.
Callable –> This interface only contains the call() method.
Java SE 8 included four main kinds of functional interfaces.
i) Consumer
ii) Predicate
iii) Function
iv) Supplier
3) Introduced and Improved APIs:
a) Stream API: Efficient Data Manipulation.
a) Stream API: Efficient Data Manipulation.
Stream API is introduced in Java 8 and is used to process collections of objects with the functional style of coding using the lambda expression.
The Stream API, introduced in Java 8, facilitates efficient data manipulation and transformation using a sequence of operations that can be performed in parallel or sequentially.
10 Ways to Create a Stream in Java
Using Collection - list.stream()
Create a stream from specified values - Stream.of(T…t)
Create stream from an array - Stream.of() and Arrays.stream()
Create an empty stream using - Stream.empty()
Create a Stream using - Stream.builder()
Create an infinite Stream using - Stream.iterate()
Create an infinite Stream using Stream.generate() method
Create stream from a Pattern using Predicate - list.stream().filter(predicate)
Create stream from Iterator -
Create stream from Iterable
Difference Between map() And flatMap() In Java Stream
In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output.
Both of the functions map() and flatMap are used for transformation and mapping operations.
map():
The function passed to map() operation returns a single value for a single input.
One-to-one mapping occurs in map().
Only perform the mapping
Produce a stream of value.
map() is used only for transformation.
flatMap():
The function you pass to flatmap() operation returns an arbitrary number of values as the output.
One-to-many mapping occurs in flatMap().
Perform mapping as well as flattening.
Produce a stream of stream value.
flatMap() is used both for transformation and mapping.
Parallel vs Sequential Stream in Java
A stream in Java is a sequence of objects which operates on a data source such as an array or a collection and supports various methods.
Stream supports many aggregate operations like filter, map, limit, reduce, find, and match to customize the original data into a different form according to the need of the programmer.
The operations performed on a stream do not modify its source hence a new stream is created according to the operation applied to it.
The new data is a transformed copy of the original form.
Sequential Stream
Sequential Streams are that use a single thread to process the pipelining.
stream() method returns a sequential stream in Java.
Parallel Stream
Parallel stream leverage multi-core processors, which increases its performance.
The simple ways to obtain a parallel stream is by invoking the parallelStream() method of Collection interface.
Another way is to invoke the parallel() method of BaseStream interface on a sequential stream.
Note: If we want to make each element in the parallel stream to be ordered, we can use the forEachOrdered() method, instead of the forEach() method.
Java 8 under the package java.time introduced a new date-time API
c) Collection API Improvements: Enhanced Methods for Collections (e.g., removeIf, replaceAll).
1) Local : Simplified date-time API with no complexity of timezone handling.
LocalDate/LocalTime and LocalDateTime API : Use it when time zones are NOT required.
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatedDateTime = current.format(format);
2) Zoned : Specialized date-time API to deal with various timezones.
Zoned date-time API : Use it when time zones are to be considered
ZoneId tokyo = ZoneId.of("Asia/Tokyo");
ZonedDateTime currentZone = ZonedDateTime.now();
ZonedDateTime tokyoZone = currentZone.withZoneSameInstant(tokyo);
Period and Duration classes :
Period : It deals with date based amount of time.
Duration : It deals with time based amount of time.
ChronoUnits Enum : java.time.temporal.ChronoUnit enum is added in Java 8 to replace integer values used in old API to represent day, month etc.
TemporalAdjuster : It is used to perform various date related operations.
drawbacks of old date-time API :
1) Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn’t have setter methods.
2) Less operations
The forEach Method
Collection.removeIf
The Iterator.forEachRemaining Method
The Collection.SplitIterator Interface
Traversing Individually (via tryAdvance)
Traversing in Bulk (via forEachRemaining)
Parallel Processing (via a SplitIterator)
List Improvements:
List.sort
List.replaceAll
Map improvements:
getOrDefault
putIfAbsent
replace
replaceAll
Compute
computeIfPresent/computeIfAbsent
remove
d) Concurrency API Improvements: New classes for parallel processing (e.g., CompletableFuture).
Java Concurrency API is a set of Java packages and classes developed to create multi-threaded applications.
Java Concurrency API is a set of Java packages and classes developed to create multi-threaded applications.
It was introduced in Java 5 and is aimed to make writing easier for concurrent and parallel code in Java.
The Java Concurrency API provide high-level abstractions for building multi-threaded applications in Java.
A few key components of the Concurrency API:
Executor Framework
Concurrent Collections
Synchronization Utilities
Atomic Variables
Fork/Join Framework
Java 8 has added the ‘CompletableFuture’ class in the ‘java.util.concurrent’ package.
4) Optional Class: Handle null values safely.
Static Methods provided by Optional Class :
empty()
of(T t)
ofNullable(T t)
Instance Methods provided by the Optional Class :
get()
ifPresent(Consumer c)
filter(Predicate p)
flatMap(Function f)
isPresent()
map(Function f)
orElse(T t)
orElseGet(Supplier s)
orElseThrow(Supplier s)
equals()
hashCode()
toString()
5) forEach() Method in Iterable Interface: Executes an action for each element in a Collection.
6) Default Methods: Evolve interfaces without breaking compatibility.
The default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.
The default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.
Default methods are also known as defender methods or virtual extension methods.
7) Static Methods: Allows adding methods with default implementations to interfaces.
8) Method References: Refer to methods easily.
Method reference is a shorthand notation of a lambda expression to call a method.
There are four types of method references that are as follows:
1) Static Method Reference
2) Instance Method Reference of a particular object
3) Instance Method Reference of an arbitrary object of a particular type
4) Constructor Reference.
9) Nashorn JavaScript Engine
Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8.
Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino.
For Nashorn engine, Java 8 introduced one new command-line tool i.e.jjs.
Operations:
Providing JavaScript variable from Java Code
Calling JavaScript function from Java code
Comments
Post a Comment