0% found this document useful (0 votes)
15 views17 pages

Key Features of Java 8

java 8 documentation

Uploaded by

tnsubramanya7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views17 pages

Key Features of Java 8

java 8 documentation

Uploaded by

tnsubramanya7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 8 Features

Oracle released a new version of Java as Java 8 in March 18, 2014. It


was a revolutionary release of the Java for software development
platform. It includes various upgrades to the Java programming, JVM,
Tools and libraries.

ava 8 Programming Language Enhancements


Java 8 provides following features for Java Programming:
o​ Lambda expressions,
o​ Method references,
o​ Functional interfaces,
o​ Stream API,
o​ Default methods,
o​ Base64 Encode Decode,
o​ Static methods in interface,
o​ Optional class,
o​ Collectors class,
o​ ForEach() method,
o​ Nashorn JavaScript Engine,
o​ Parallel Array Sorting,
o​ Type and Repating Annotations,
o​ IO Enhancements,
o​ Concurrency Enhancements,
o​ JDBC Enhancements etc.
Lambda Expressions
Lambda expression helps us to write our code in functional style. It
provides a clear and concise way to implement SAM interface(Single
Abstract Method) by using an expression. It is very useful in collection
library in which it helps to iterate, filter and extract data.
Functional Interface
Lambda expression provides implementation of functional interface. An
interface which has only one abstract method is called functional
interface. Java provides an anotation @FunctionalInterface, which is
used to declare an interface as functional interface.
Java Default Methods

Java provides a facility to create default methods inside the interface.


Methods which are defined inside the interface and tagged with default
are known as default methods. These methods are non-abstract methods.
Java Default Method Example
1.​ interface Sayable{
2.​ // Default method
3.​ default void say(){
4.​ [Link]("Hello, this is default method");
5.​ }
6.​ // Abstract method
7.​ void sayMore(String msg);
8.​ }
9.​ public class DefaultMethods implements Sayable{
10.​ public void sayMore(String msg){ // implementing abstract m
ethod
11.​ [Link](msg);
12.​ }
13.​ public static void main(String[] args) {
14.​ DefaultMethods dm = new DefaultMethods();
15.​ [Link](); // calling default method
16.​ [Link]("Work is worship"); // calling abstract method
17.​
18.​ }
19.​ }
Static Methods inside Java 8 Interface
You can also define static methods inside the interface. Static methods
are used to define utility methods. The following example explain, how
to implement static method in interface?
1.​ interface Sayable{
2.​ // default method
3.​ default void say(){
4.​ [Link]("Hello, this is default method");
5.​ }
6.​ // Abstract method
7.​ void sayMore(String msg);
8.​ // static method
9.​ static void sayLouder(String msg){
10.​ [Link](msg);
11.​ }
12.​ }
13.​ public class DefaultMethods implements Sayable{
14.​ public void sayMore(String msg){ // implementing abstract met
hod
15.​ [Link](msg);
16.​ }
17.​ public static void main(String[] args) {
18.​ DefaultMethods dm = new DefaultMethods();
19.​ [Link](); // calling default method
20.​ [Link]("Work is worship"); // calling abstract method
21.​ [Link]("Helloooo..."); // calling static method
22.​ }
23.​ }

Why use Lambda Expression


1.​ To provide the implementation of Functional interface.
2.​ Less coding.

Java Lambda Expression Syntax


1.​ (argument-list) -> {body}
2.​ ava lambda expression is consisted of three components.
3.​ 1) Argument-list: It can be empty or non-empty as well.
4.​ 2) Arrow-token: It is used to link arguments-list and body of
expression.
5.​ 3) Body: It contains expressions and statements for lambda
expression.
6.​ No Parameter Syntax
7.​ () -> {
8.​ //Body of no parameter lambda
9.​ }

One Parameter Syntax

1.​ (p1) -> {


2.​ //Body of single parameter lambda
3.​ }

Two Parameter Syntax


1.​ (p1,p2) -> {
2.​ //Body of multiple parameter lambda
3.​ }
Let's see a scenario where we are not implementing Java lambda
expression. Here, we are implementing an interface without using
lambda expression.

Without Lambda Expression

interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;

//without lambda, Drawable implementation using anonymous class


Drawable d=new Drawable(){
public void draw(){[Link]("Drawing "+width);}
};
[Link]();
}
}
Java Lambda Expression Example

@FunctionalInterface //It is optional


interface Drawable{
public void draw();
}

public class LambdaExpressionExample2 {


public static void main(String[] args) {
int width=10;

//with lambda
Drawable d2=()->{
[Link]("Drawing "+width);
};
[Link]();
}
}
forEach
Java provides a new method forEach() to iterate the elements. It is
defined in Iterable and Stream interfaces
It is a default method defined in the Iterable interface. Collection classes
which extends Iterable interface can use forEach() method to iterate
elements.
This method takes a single parameter which is a functional interface. So,
you can pass lambda expression as an argument.

forEach() Signature in Iterable Interface


default void forEach(Consumer<super T>action)

1.​ import [Link];


2.​ import [Link];
3.​ public class ForEachExample {
4.​ public static void main(String[] args) {
5.​ List<String> gamesList = new ArrayList<String>();
6.​ [Link]("Football");
7.​ [Link]("Cricket");
8.​ [Link]("Chess");
9.​ [Link]("Hocky");
10.​ [Link]("------------Iterating by passing lambda
expression--------------");
11.​ [Link](games -> [Link](games));
12.​
13.​ }
14.​ }
Java 8 forEach() example 2

1.​ import [Link];


2.​ import [Link];
3.​ public class ForEachExample {
4.​ public static void main(String[] args) {
5.​ List<String> gamesList = new ArrayList<String>();
6.​ [Link]("Football");
7.​ [Link]("Cricket");
8.​ [Link]("Chess");
9.​ [Link]("Hocky");
10.​ [Link]("------------Iterating by passing method refere
nce---------------");
11.​ [Link]([Link]::println);
12.​ }
13.​ }

Java Date and Time


The [Link], [Link], [Link] and [Link] packages contains classes
for representing date and time. Following classes are important for
dealing with date in Java.
Java 8 Date/Time API
Java has introduced a new Date and Time API since Java 8. The
[Link] package contains Java 8 Date and Time classes.
1.​ import [Link];
2.​ public class LocalDateExample1 {
3.​ public static void main(String[] args) {
4.​ LocalDate date = [Link]();
5.​ LocalDate yesterday = [Link](1);
6.​ LocalDate tomorrow = [Link](2);
7.​ [Link]("Today date: "+date);
8.​ [Link]("Yesterday date: "+yesterday);
9.​ [Link]("Tomorrow date: "+tomorrow);
10.​ }
11.​ }

O/P
Today date: 2017-01-13
Yesterday date: 2017-01-12
Tomorrow date: 2017-01-14

Java StringJoiner

Java added a new final class StringJoiner in [Link] package. It is used


to construct a sequence of characters separated by a delimiter. Now, you
can create string by passing delimiters like comma(,), hyphen(-) etc. You
can also pass prefix and suffix to the char sequence.
1.​ // importing StringJoiner class
2.​ import [Link];
3.​ public class StringJoinerExample {
4.​ public static void main(String[] args) {
5.​ StringJoiner joinNames = new StringJoiner(","); // passing comma(,
) as delimiter
6.​
7.​ // Adding values to StringJoiner
8.​ [Link]("Rahul");
9.​ [Link]("Raju");
10.​ [Link]("Peter");
11.​ [Link]("Raheem");
12.​
13.​ [Link](joinNames);
14.​ }
15.​ }

Rahul,Raju,Peter,Raheem

Java StringJoiner Example: adding prefix and suffix

Java 8 Stream
Java provides a new additional package in Java 8 called [Link].
This package consists of classes, interfaces and enum to allows
functional-style operations on the elements. You can use stream by
importing [Link] package.
o​ Stream does not store elements. It simply conveys elements from a source such as
a data structure, an array, or an I/O channel, through a pipeline of computational
operations.
o​ Stream is functional in nature. Operations performed on a stream does not modify
it's source. For example, filtering a Stream obtained from a collection produces a
new Stream without the filtered elements, rather than removing elements from the
source collection.
o​ Stream is lazy and evaluates code only when required.
o​ The elements of a stream are only visited once during the life of a stream. Like an
Iterator, a new stream must be generated to revisit the same elements of the
source.

You can use stream to filter, collect, print, and convert from one data structure to other
etc. In the following examples, we have apply various operations with the help of stream.

Java Example: Filtering Collection without using Stream

1.​ import [Link].*;


2.​ class Product{
3.​ int id;
4.​ String name;
5.​ float price;
6.​ public Product(int id, String name, float price) {
7.​ [Link] = id;
8.​ [Link] = name;
9.​ [Link] = price;
10.​ }
11.​ }
12.​ public class JavaStreamExample {
13.​ public static void main(String[] args) {
14.​ List<Product> productsList = new ArrayList<Product>();
15.​ //Adding Products
16.​ [Link](new Product(1,"HP Laptop",25000f));
17.​ [Link](new Product(2,"Dell Laptop",30000f));
18.​ [Link](new Product(3,"Lenevo Laptop",28000f));
19.​ [Link](new Product(4,"Sony Laptop",28000f));
20.​ [Link](new Product(5,"Apple Laptop",90000f));
21.​ List<Float> productPriceList = new ArrayList<Float>();
22.​ for(Product product: productsList){
23.​
24.​ // filtering data of list
25.​ if([Link]<30000){
26.​ [Link]([Link]); // adding price to a p
roductPriceList
27.​ }
28.​ }
29.​ [Link](productPriceList); // displaying data
30.​ }
31.​ }

[25000.0, 28000.0, 28000.0]

Java Stream Example: Filtering Collection by using Stream


Here, we are filtering data by using stream. You can see that code is
optimized and maintained. Stream provides fast execution.
1.​ import [Link].*;
2.​ import [Link];
3.​ class Product{
4.​ int id;
5.​ String name;
6.​ float price;
7.​ public Product(int id, String name, float price) {
8.​ [Link] = id;
9.​ [Link] = name;
10.​ [Link] = price;
11.​ }
12.​ }
13.​ public class JavaStreamExample {
14.​ public static void main(String[] args) {
15.​ List<Product> productsList = new ArrayList<Product>();
16.​ //Adding Products
17.​ [Link](new Product(1,"HP Laptop",25000f));
18.​ [Link](new Product(2,"Dell Laptop",30000f));
19.​ [Link](new Product(3,"Lenevo Laptop",28000f));
20.​ [Link](new Product(4,"Sony Laptop",28000f));
21.​ [Link](new Product(5,"Apple Laptop",90000f));
22.​ List<Float> productPriceList2 =[Link]()
23.​ .filter(p -> [Link] > 30000)// filtering data
24.​ .map(p->[Link]) // fetching price
25.​ .collect([Link]()); // collecting as list

26.​ [Link](productPriceList2);
27.​ }
28.​ }
Java Stream Iterating Example

You can use stream to iterate any number of times. Stream provides
predefined methods to deal with the logic you implement. In the
following example, we are iterating, filtering and passed a limit to fix
the iteration.

1.​ import [Link].*;


2.​ public class JavaStreamExample {
3.​ public static void main(String[] args){
4.​ [Link](1, element->element+1)
5.​ .filter(element->element%5==0)
6.​ .limit(5)
7.​ .forEach([Link]::println);
8.​ }
9.​ }

5
10
15
20
25

Java Stream Example: Filtering and Iterating Collection


//Findfirst()
by using Stream API solve this:.....
reduce() Method in Collection
Find Max and Min Product Price
count() Method in Collection
Convert List into Set
Convert List into Map
Method Reference in stream
normal stream and parallel stream

Java Method References


Java provides a new feature called method reference in Java 8. Method reference is used
to refer method of functional interface. It is compact and easy form of lambda expression.
Each time when you are using lambda expression to just referring a method, you can
replace your lambda expression with method reference. In this tutorial, we are explaining
method reference concept in detail.

Types of Method References


There are following types of method references in java:
1.​ Reference to a static method.
2.​ Reference to an instance method.
3.​ Reference to a constructor.
interface Sayable{
​ void say();
}
public class MethodReference {
​ public static void saySomething(){
​ ​ [Link]("Hello, this is static method.");
​ }
​ public static void main(String[] args) {
​ // Referring static method
​ Sayable sayable = MethodReference::saySomething;
​ // Calling interface method
​ [Link]();
​ }
}

Common questions

Powered by AI

Java 8 facilitates functional programming primarily through Lambda expressions and enhanced interfaces like Functional Interfaces and Default Methods. Lambda expressions introduce functional programming elements like first-class functions, enabling concise syntax to pass behavior as data. Functional Interfaces act as the target types for Lambda expressions, promoting the use of single method functional-style coding. Furthermore, Default Methods in interfaces allow code reuse and method extension without violating existing code's integrity, which aligns with the principles of functional programming .

Method references enhance the functionality of Lambda expressions by providing a more concise way to express Lambda expressions that just call existing methods. Instead of writing a Lambda expression to call a method, developers can use a method reference to refer directly to it. This becomes particularly efficient when using predefined functional interfaces consisting of operations repeatedly written throughout the code, thus promoting code reuse and clarity .

The Optional class in Java 8 is a container object which may or may not contain a value, helping to avoid NullPointerExceptions. It encourages developers to explicitly deal with cases where a value may be absent, rather than assuming non-null values everywhere in the code. By providing methods like isPresent(), ifPresent(), and orElse(), Optional promotes a coding style that handles the absence of values more gracefully, enhancing code clarity and safety .

Java 8 introduced a new Date and Time API under the java.time package, which addresses the shortcomings of the old java.util.Date and java.util.Calendar classes by providing an immutable, type-safe, and more comprehensive structure. It includes classes such as LocalDate, LocalTime, and LocalDateTime for more precise manipulation and formatting, and supports time zone and leap second considerations, making date and time handling more intuitive and less error-prone .

Java 8 introduced several concurrency enhancements like the CompletableFuture API and improvements to the Fork/Join framework, which significantly impact handling asynchronous computations more effectively. CompletableFuture provides the ability to compose, combine, and control asynchronous actions, improving upon inadequate solutions in prior versions. Moreover, the Fork/Join improvements allow better exploitation of parallelism, promoting scalable concurrent applications. These features address limitations in thread management and provide more efficient, non-blocking operations, enhancing overall concurrency capabilities .

Lambda expressions and method references reduce verbosity by eliminating the need for boilerplate code associated with anonymous classes. Lambda expressions replace anonymous classes in implementing functional interfaces, allowing code to be expressed more concisely. Method references, being a shorthand for lambda expressions, can refer methods directly, further simplifying the process of method invocation .

The Stream API in Java 8 introduces a functional programming approach to processing collections. It allows developers to perform operations such as filtering, mapping, and reducing on collections in a declarative manner. Streams enable lazy evaluation, meaning that the execution can be optimized by minimizing the number of operations. This leads to more efficient and readable code compared to traditional looping and conditionals .

Default methods in Java 8 allow interfaces to have concrete methods with a default implementation. This transforms interface design by enabling new methods to be added to existing interfaces without breaking the implementations of existing clients. It also supports code reuse by providing developers with the means to define a method right in the interface without forcing all implementing classes to override it, which can lead to cleaner and more maintainable code .

Java 8 introduced several enhancements including Lambda expressions, Method references, Functional interfaces, Stream API, and Default methods. Collectively, they provide support for functional programming, allowing developers to write clearer and more concise code. For instance, Lambda expressions enable implementation of functional interfaces with less code, while the Stream API facilitates functional-style operations on data collections, leading to efficient data processing .

Static methods in interfaces were introduced in Java 8 to offer a way to provide utility methods associated with the interface without needing implementation in classes implementing the interface. These methods serve as helpers or factories, offering functionality that is pertinent to the interface but does not necessitate instance-specific behavior. By doing so, they encourage more organized and modular code, allowing relevant methods to be grouped with their associated types .

You might also like