0% found this document useful (0 votes)
46 views42 pages

Java 8 Features

Uploaded by

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

Java 8 Features

Uploaded by

aryany1303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Java 8 Features

• Functional Interfaces
• Lambda Expression
• Method References
• Stream API
• Default Methods
• Static Method
• Base64 Encode and Decode
• Etc.
Advantages of Java8 new features

• Developers may now take use of new functional programming techniques


introduced in Java 8 to create code that is both shorter and more expressive.
• Lambda expressions, functional interfaces, the Stream API, the Reference to
Methods, and the Optional class are all examples of such features.
Lambda Expression
 The Lambda expression is used to provide the implementation of a
functional interface.
 It helps to iterate, filter and extract data from collection.
 In case of lambda expression, we don't need to define the method again for
providing the implementation.
 It saves a lot of code i.e. less coding.
Java Lambda Expression Syntax

(argument-list) -> {body}

Java lambda expression is consisted of three components:

1) Argument-list: It can be empty or non-empty as well.


2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.
Types of Lambda Expression
 A body with single expression
 A body that consists of block of code

No parameter Syntax:
( ) -> {
//Body of no parameter lambda
}
One Parameter Syntax
(p1) -> {
//Body of single parameter lambda
}
Two Parameter Syntax
(p1,p2) -> {
//Body of multiple parameter lambda
}
Example of Lambda Expression with one
parameter
@functional interface
interface NumericTest{
boolean test(int n);
}

public class LambdaDemo1 {


public static void main(String args[]) {

NumericTest isEven= (n) -> (n%2)==0;

if(isEven.test(10)) System.out.println("10 is even");


if(!isEven.test(9)) System.out.println("9 is not even");
}
}
What is Functional Interface in Java?
 An Interface that contains exactly one abstract method is known as functional
interface.
 It can have any number of default and static methods but can contain only one
abstract method.
 It is known as Single Abstract Method Interfaces(SAM).
 It helps in functional programming task.
 Interface with an annotation called @FunctionalInterface.
 We can invoke Lambda expression by using functional interface.
 Runnable, ActionListener, Consumer<T>, and Comparable<T> are some
examples of functional interfaces.
How to define Functional Interface?
 No need to use the abstract keyword, by default, method defined inside the
interface is abstract only.
@FunctionalInterface
interface Sample{
void display(String msg);
}
public class FInterfaceDemo implements Sample {
public void display(String msg){
System.out.println(msg);
}
public static void main(String[] args) {
FInterfaceDemo f = new FInterfaceDemo();
f.display("functional interface demo");
} }
Advantage of Annotation (@)

• It restrict the interface to be a functional interface.


• e.g. if one person has defined one abstract method and is using Lambda
expression and another person added one more abstract method in the same
functional interface, then all lambda expressions will have errors.
Default Methods
 Before Java 8, interfaces could have only abstract methods.
 The implementation of these methods has to be provided in a separate class.
 So, if a new method is to be added in an interface, then its implementation code has to
be provided in class implementing the same interface.
 To overcome this issue, Java 8 has introduced the concept of default methods which
allow the interfaces to have methods with implementation without affecting the
classes that implement the interface.
 Default methods are also known as defender methods or virtual extension methods.
Default Methods: Example Java program
Static Method in Interface
• Java 8 also allows us to define and implement static methods in interfaces.
• Since static methods don’t belong to a particular object, they’re not part of the API
of the classes implementing the interface
• they have to be called by using the interface name preceding method name.
Java Predefined-Functional Interfaces
Java provides predefined functional interfaces to deal with functional programming
by using lambda and method references.
Interface Description
BiConsumer<T,U> It represents an operation that accepts two input arguments and
returns no result.
Consumer<T> It represents an operation that accepts a single argument and
returns no result.
Function<T,R> It represents a function that accepts one argument and returns a
result.
Predicate<T> It represents a predicate (boolean-valued function) of one
argument.
BiFunction<T,U,R> It represents a function that accepts two arguments and returns a
result.
BinaryOperator<T> It represents an operation upon two operands of the same data type.
It returns a result of the same type as the operands.
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.
• Three types are there:-
-Reference to a static method.
-Reference to an instance method.
-Reference to a constructor.
Reference to a Static Method
• A static method reference refers to a static method in a specific class.
• Its syntax is className::staticMethodName
• Where classname identifies the class
• staticMethodName identifies the method

public class MethodReference2 {


public static void ThreadStatus(){
System.out.println("Thread is running...");
}
public static void main(String[] args) {
Thread t2=new Thread(MethodReference2::ThreadStatus);
t2.start();
}
}
Reference to an instance method
• like static methods, you can refer instance methods also
• The syntax is---

containingObject::instanceMethodName

public class InstanceMethodReference2 {


public void printnMsg(){
System.out.println("Hello, this is instance method");
}
public static void main(String[] args) {
Thread t2=new Thread(new InstanceMethodReference2()::printnMsg);
t2.start();
}
}
Reference to a constructor
• Refer a constructor by using the new 1.interface Messageable{
keyword. 2. Message getMessage(String msg);
3.}
• we are referring constructor with the 4.class Message{
help of functional interface. 5. Message(String msg){
• The syntax is --- 6. System.out.print(msg);
7. }
ClassName::new 8.}
9.public class ConstructorReference {
10. public static void main(String[] args) {
11. Messageable hello = Message::new;
12. hello.getMessage("Hello");
13. }
14.}
Stream API
• Introduced in Java 8, Stream API is used to process collections of objects.
• A stream in Java is a sequence of objects that supports various methods which can
be pipelined to produce the desired result.
• A stream operates on a data source, such as an array or a collection.
• A stream, itself, never provides storage for the data.

Uses of Stream API

1. Stream API is a way to express and process collections of objects.


2. Enable us to perform operations like filtering, mapping, reducing and sorting.
How to Create Java Stream?
Java Stream Creation is one of the most basic steps before considering the
functionalities of the Java Stream. Below is the syntax given on how to declare Java
Stream.
Syntax
Stream<T> stream;
Here T is either a class, object, or data type depending upon the declaration.
You can use stream by importing java.util.stream package
Stream API Features
 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.
 Streams don’t change the original data structure, they only provide the result as per
the pipelined methods.
 Each intermediate operation is lazily executed and returns a stream as a result, hence
various intermediate operations can be pipelined. Terminal operations mark the end
of the stream and return the result.
 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.
Stream API
Stream Operations
Stream operations are divided into two types:-
1. Intermediate operations
2. Terminate operations

Intermediate-
• Methods are chained together.
• Intermediate operations transform a stream into another stream.
• It enables the concept of filtering where one method filters data and passes it to
another method after processing.

Terminal- Terminal Operations are the type of Operations that return the result. These
Operations are not processed further just return a final result value.
Few Intermediate Operations
Method Meaning Syntax
map() The map method is used to return a List number = Arrays.asList(2,3,4,5);
stream consisting of the results of List square = number.stream().map(x-
applying the given function to the >x*x).collect(Collectors.toList());
elements of this stream.
filter() The filter method is used to select List names =
elements as per the Predicate passed as Arrays.asList("Reflection","Collection","St
an argument. ream");
List result = names.stream().filter(s-
>s.startsWith("S")).collect(Collectors.toList
());
sort() The sorted method is used to sort the List names =
stream. Arrays.asList("Reflection","Collection","St
ream");
List result =
names.stream().sorted().collect(Collectors.t
oList());
Few Terminal Operations
Method Meaning Syntax
collect() The collect method is used to return the List number = Arrays.asList(2,3,4,5,3);
result of the intermediate operations Set square = number.stream().map(x-
performed on the stream. >x*x).collect(Collectors.toSet());
forEach() The forEach method is used to iterate List number = Arrays.asList(2,3,4,5);
through every element of the stream. number.stream().map(x-
>x*x).forEach(y-
>System.out.println(y));
reduce() The sorted method is used to sort the List number = Arrays.asList(2,3,4,5);
streThe reduce method is used to reduce int even = number.stream().filter(x->x
the elements of a stream to a single value. %2==0).reduce(0,(ans,i)-> ans+i);
The reduce method takes a
BinaryOperator as a parameter.
Stream Interface
Stream Interface
Stream Interface
Stream Interface
Example Java program to show intermediate
operations
Reduction operations
• Many times, we need to perform operations where a stream reduces to
single resultant value, for example, maximum, minimum, sum, product,
etc.
• Reducing is the repeated process of combining all elements.
• sum(), min(), max(), count() etc. are some examples of reduce
operations.
Base64 Encode and Decode
• Base 64 is an encoding scheme that converts binary data into text format so that
encoded textual data can be easily transported over network un-corrupted and
without any data loss.
• Java provides a class Base64 to deal with encryption.
• We can encrypt and decrypt data by using provided methods.
• java.util.Base64 need to be imported in source file to use its methods.
• There are 3 types of encoding and decoding capabilities as standard.
-Base or Simple Type
-URL Encoding/Decoding
-MIME Encoding/Decoding
Java 8 Basic Base64
• It uses the Base64 alphabet specified by Java in RFC 4648 and RFC 2045 for
encoding and decoding operations.
• The basic encoder keeps things simple and encodes the input as-is, without any
line separation.
• The encoder maps the input to a set of characters in the A-Za-z0-9+/ character set.
• The decoder rejects data that contains characters outside the base64 alphabet.
encoding String--

Decoding String--
Java 8 Base64 Encoding Without Padding

• In Base64 encoding, the length of an output-encoded String must be a multiple of


four. If necessary, the encoder adds one or two padding characters (=) at the end of
the output as needed in order to meet this requirement.
• Upon decoding, the decoder discards these extra padding characters.
• we need to skip the padding of the output. For instance, the resulting String will
never be decoded back. So, we can simply choose to encode without padding.
Java 8 URL Encoding and decoding
• The URL encoding is the same as Basic encoding the only difference is that it
encodes or decodes the URL and Filename safe Base64 alphabet and does not add
any line separation.
ForEach Method
• Java provides a new method forEach() to iterate the elements. It is defined in
Iterable and Stream interface. It is a default method defined in the Iterable
interface. Collection classes which extends Iterable interface can use forEach loop
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)
Try-with-resources
• This feature allows us to declare resources to be used in a try block with the
assurance that the resources will be closed after the execution of that block.
• The resources declared need to implement the AutoCloseable interface.
• Simply put, to be auto-closed, a resource has to be both declared and initialized
inside the try:
Try-with-resources
Try-with-resources can replace try-catch-finally block.
try-with-resources With Multiple Resources
We can declare multiple resources just fine in a try-with-resources block by
separating them with a semicolon:
Type Annotations
• As of the Java SE 8 release, annotations can also be applied to any type use.
• This means that annotations can be used anywhere you use a type.
• Type annotations were created to support improved analysis of Java programs way
of ensuring stronger type checking.
• For example, if you want to avoid NullPointerException in your code, you can
declare a string variable like this:

@NonNull String str;


Repeating Annotations
• Java allows you to repeating annotations in your source code.
• It is helpful when you want to reuse annotation for the same class.
• You can repeat an annotation anywhere that you would use a standard annotation.
• these are stored in a container annotation that is automatically generated by the
Java compiler.
• In order for the compiler to do this, two declarations are required in your code.
Declare a repeatable annotation type
• Declaring of repeatable annotation type must be marked with the @Repeatable
meta-annotation.
• a custom annotations is defined @Game repeatable annotation type.

1.@Repeatable(Games.class)
2.@interfaceGame{
3. String name();
4. String day();
5.}
Declare the containing annotation type
• Containing annotation type must have a value element with an array type.
• The component type of the array type must be the repeatable annotation type.
• Example- declaring Games containing annotation type:

1.@interfaceGames{
2. Game[] value();
3.}

You might also like