0% found this document useful (0 votes)
2 views26 pages

12 -Java 8-11

This document provides an overview of key features introduced in Java 8 to 11, including Lambda Expressions, Method References, Functional Interfaces, Default Methods, Date Time API, Base64 encoding, Stream API, forEach() method, and the Optional class. Each feature is explained with definitions, characteristics, and code examples. The document serves as a comprehensive guide for understanding these Java enhancements and their applications.

Uploaded by

chhungsim.chuo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
2 views26 pages

12 -Java 8-11

This document provides an overview of key features introduced in Java 8 to 11, including Lambda Expressions, Method References, Functional Interfaces, Default Methods, Date Time API, Base64 encoding, Stream API, forEach() method, and the Optional class. Each feature is explained with definitions, characteristics, and code examples. The document serves as a comprehensive guide for understanding these Java enhancements and their applications.

Uploaded by

chhungsim.chuo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 26

Java

8 - 11

Prepared by Java Team


Contents

1. Lambda Expression 8. forEach() Method


2. Method References 9. Optional class
3. Functional Interface
4. Default Method
5. Date Time API
6. Base 64
7. Stream API
1. Lambda Expression
● Lambda expression is a new and important feature of Java
which was included in Java SE 8. It provides a clear and
concise way to represent one method interface using an
expression. It is very useful in collection library. It helps to
iterate, filter and extract data from collection.
● The Lambda expression is used to provide the
implementation of an interface which has functional
interface. It saves a lot of code. In case of lambda
expression, we don't need to define the method again for
providing the implementation. Here, we just write the
(args1,code.
implementation args2, args3, ...) ->
{ body }
1. Lambda Expression (Cont.)
● Important characteristics of a lambda expression:
○ Optional type declaration − No need to declare the
type of a parameter. The compiler can inference the
same from the value of the parameter.
○ Optional parentheses around parameter − No need
to declare a single parameter in parenthesis. For multiple
parameters, parentheses are required.
○ Optional curly braces − No need to use curly braces in
expression body if the body contains a single statement.
For multiple statements, curly braces are required.
1. Lambda Expression (Cont.)
● Important characteristics of a lambda expression: (Cont.)
○ Optional return keyword − The compiler
automatically returns the value if the body has a single
expression to return the value. Curly braces are
required to indicate that expression returns a
public class LambdaDemo {
value.
public static void main(String[] args) {
GreetingService gs = msg ->
{ System.out.println(msg); };
gs.sayMessage("Hello");
}
}
interface GreetingService {
void sayMessage(String msg);
}
2. 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.
● There are following types of method references in java:
○ Reference to a static method.
○ Reference to an instance method.
2. Method References (Cont.)
● Reference to static method
public class MethodReferenceDemo {
public static void saySomething() {
System.out.println("Hello everyone!");
}

public static void main(String[] args) {


Sayable sayable =
MethodReferenceDemo::saySomething;
sayable.say();
}
}
interface Sayable{
void say();
}
2. Method References (Cont.)
● Reference to instance method
public class MethodReferenceDemo {
public void saySomething() {
System.out.println("Hello everyone!");
}

public static void main(String[] args) {


MethodReferenceDemo mr = new
MethodReferenceDemo();
Sayable sayable = mr::saySomething;
sayable.say();
}
}
interface Sayable{
void say();
}
2. Method References (Cont.)
● Reference to constructor
public class ConstructorReference {
public static void main(String[]
args) {
Messageable msg = Message::new;
msg.getMessage("Hello");
}
}
interface Messageable {
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.println(msg);
}
}
3. Functional Interface
● An Interface that contains exactly one abstract method is
known as functional interface.
● It can have any number of default, static methods but
can contain only one abstract method.
● Functional Interface is also known as Single Abstract
Method Interfaces or SAM Interfaces.
● It is a new feature in Java, which helps to achieve functional
programming approach.
3. Functional Interface (Cont.)
Example:
public class FunctionalInterfaceDemo {
void say(String msg){
System.out.println(msg);
}
public static void main(String[] args) {
FunctionalInterfaceDemo fid = new
FunctionalInterfaceDemo();
fid.say("Hello there");
}
}
@FunctionalInterface
interface sayable {
void say(String msg);
}
4. Default Method
● 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.
4. Default Method (Cont.)
Example:
public class DefaultMethod implements Sayable{
public void sayMore(String msg){ // implementing abstract
method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethod dm = new DefaultMethod();
dm.say(); // call default method
dm.sayMore("Hello world"); // call abstract method
}
}
interface Sayable{
default void say(){ // Default method
System.out.println("Hello, this is default method");
}
void sayMore(String msg); // Abstract method
}
5. Date Time API
● New API for Date and Time was new introduce since java 8
which come to replace the old API: java.util.Date and
java.util.Calendar to eliminate the existing issue in Date
and Calendar API.
● Date-Time API is under the package: java.time which
contains 2 main classes:
○ Local: it represent the local date, local time from the
context. And there are 3 subclass that commonly use
are: LocalDate, LocalTime and LocalDateTime.
○ Zone: it represent the date and time with the various
timezoned, it can help us to set the date and time base
5. Date Time API (Cont.)
● Example of Using Local Date-Time API

public static void main(String[] args) {


LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: "+currentTime);
LocalDate date = currentTime.toLocalDate();
System.out.println("date: "+date);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int second = currentTime.getSecond();
System.out.println("Month: "+month+" day: "+day+" seconds:
"+second);
}
5. Date Time API (Cont.)
Example of Using Zone Date-Time API
public static void main(String[] args) {
ZonedDateTime date1;
date1 =
ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Karachi]");
System.out.println("date1: " + date1);

ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);

ZoneId currentZone = ZoneId.systemDefault();


System.out.println("CurrentZone: " + currentZone);
}
6. Base64
● Since Java 8, Java enable the various ways to encrypt and
decrypt data by using Base64 API.
● To Encrypt data or decrypt data, we use encoder or decoder
in Base64 API.
● Base64 is a binary-to-text encoding scheme that takes raw
input bytes and encodes it in a radix-64 representation,
using the characters A-Z, a-z, 0-9, and the symbols +, / and
=. Base64 encoding is used when there is a need to store or
transmit binary data over a system that only supports text
data, without losing or corrupting said data.
6. Base64 (Cont.)
● Encode data into Base64
public static void main(String[] args) {
String inputString = "hello world~";

String base64String = Base64.getEncoder()


.encodeToString(inputString.getBytes(
));
System.out.println(base64String);
}
6. Base64 (Cont.)
● Decode data from Base64
public static void main(String[] args) {
String inputString = "aGVsbG8gd29ybGR+";

String decodedString = new


String(Base64.getDecoder()
.decode(inputString));
System.out.println(decodedString);
}
7. Stream API
● Stream represents a sequence of objects from a source,
which supports aggregate operations.
● Since Java 8, Java provide new Stream API to works with
steam to filter, collect, print, and convert from source such
as a data structure, an array, or an I/O channel, through a
pipeline of computational operations.
● It give us a various to create Stream base on our actual
works such as:
○ To create Empty Stream
Stream<String> we can
streamEmpty = use empty() method:
Stream.empty();
7. Stream API
○ To create a stream of any type of Collection (Collection, List,
Set) we can use stream() method:
Example:
Collection<String> collection = Arrays.asList("a", "b",
"c");

Stream<String> stream = collection.stream();

○ We also can create stream of array by using :


Stream.of(Array[]) method:

Example:
Stream<String> streamOfArray = Stream.of("a","b","c");
8. 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.
8. forEach() Method (Cont.)
Example:
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");

gamesList.forEach(games ->
System.out.println(games));
}
9. Optional class
● Java introduced a new class Optional in jdk8.
● It provide a better alternate mechanism for a method to
indicate no result to the caller.
● It is a public final class and used to deal with
NullPointerException in Java application.
9. Optional class (Cont.)
Example:
public static void main(String[] args) {
String[] words = new String[10];
Optional<String> checkNull =
Optional.ofNullable(words[5]);
if (checkNull.isPresent()) {
String word = words[5].toLowerCase();
System.out.print(word);
}
else
System.out.println("word is null");
}
THANKS
!

You might also like