SlideShare a Scribd company logo
Major Java 8 Features
Sanjoy Kumar Roy
sanjoykr78@gmail.co
m
Agenda
Interface Improvements
Functional Interfaces
Lambdas
Method references
java.util.function
java.util.stream
Interface Improvements
Interfaces can now define static
methods.
For Example: naturalOrder method in java.util.Comparator
public interface Comparator<T> {
………
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
}
…………
}

3
Interface Improvements
(cont.)
Interfaces can define default methods
public interface A {
default void foo(){
System.out.println("Calling A.foo()");
}
}
public class MyClass implements A { }
MyClass clazz = new MyClass();
clazz.foo(); // Calling A.foo()
4
Interface Improvements
(cont.)
Multiple inheritance?
Interface A

Interface B

default void foo()

default void foo()

Class MyClass implements A, B
5
Interface Improvements
(cont.)
public interface A {
default void foo(){
System.out.println("Calling A.foo()");
}
}

CODE
FAILS

public interface B {
default void foo(){
System.out.println("Calling A.foo()");
}
}
public class MyClass implements A, B { }
6
Interface Improvements
(cont.)
This can be fixed :

Overriding in
implementation
class

public class MyClass implements A, B {
default void foo(){
System.out.println("Calling from my class.");
}
}

OR
public class MyClass implements A, B {
default void foo(){
A.super.foo();
Calling the default
implementation of method
}
foo() from interface A
}
7
Interface Improvements
(cont.)

Another Example

forEach method in java.lang.Iterable
public default void forEach(Consumer<? super T> action)
{
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}

8
Interface Improvements
(cont.)
Why do we need default methods in
Interface?
List<Person> persons = asList(
new Person("Joe"),
new Person("Jim"),
new Person("John"));
persons.forEach(p -> p.setLastName("Doe"))

9
Interface Improvements
(cont.)

Enhancing the behaviour of existing
libraries (Collections) without
breaking backwards compatibility.

10
Functional Interface
An interface is a functional interface
if it defines exactly one abstract
method.
For Example: java.lang.Runnable is a functional interface.
Because it has only one abstract method.

@FunctionalInterface
public interface Runnable {
public abstract void run();
}
11
Functional Interface
(cont.)
Functional interfaces are also called Single
Abstract Method (SAM) interfaces. Anonymous
Inner Classes can be created using these
interfaces.
public class MyAnonymousInnerClass {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(“Hello!");
}}).start();
}
}
12
Functional Interface
(cont.)
public class MyAnonymousInnerClass {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(“Hello!");
}}).start();
Unclear
}
Bit excessive
}

Cumbersome

Lambda Expressions can help us
13
How can lambda expression
help us?
But before that we need to
see:

Why are lambda
expressions being added
to Java?
14
Most pressing reason is:

Lambda expressions make
the distribute
processing of
collections over
multiple threads easier.
15
How do we process lists and
sets today ?
Collection

Iterator

What is the
issue?
16

Client
Code
Parallel
Processing
In Java 8 -

Client
Code

CODE AS A
DATA

f
Collection
f

17

f

f

f
Benefits of doing this:
 Collections can now organise
their iteration internally.
 Responsibility for
parallelisation is transferred
from client code to library
code.
18
But client code needs a simple way of
providing a function to the collection
methods.
Currently the standard way of doing
this is by means of an anonymous class
implementation of the appropriate
interface.
Using a lambda, however, the same
effect can be achieved much more
concisely.
19
public class MyAnonymousInnerClass {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(“Hello!");
}}).start();
}
}
public class MyAnonymousInnerClass {
public static void main(String[] args) {
new Thread(() -> System.out.println(“Hello!")
).start();
}
}
20
Lambda Expression
Lambda Expression (Project Lambda) is
one of the most exciting feature of
Java 8.
Remember

SAM type?

In Java lambda expression is SAM type.
Lambda expressions let us express
instances of single-method classes
more compactly.
21
So what is lambda
expression?
In mathematics and computing generally,

a lambda expression is a function.
For some
or
all
combinations
of input
values
22

It specifies

An output
value
Lambda Syntax
The basic syntax of lambda is either

(parameters) -> expression
or

(parameters) -> { statements; }
23
Some examples
(int x, int y) -> x + y

// takes two integers and returns

their sum

(x, y) -> x – y

// takes two numbers and returns their

difference

() -> 42

// takes no values and returns 42

(String s) -> System.out.println(s)
// takes a string, prints its value to the console, and returns
nothing

x -> 2 * x

// takes a number and returns the result of

doubling it

c -> { int s = c.size(); c.clear(); return s; }
// takes a collection, clears it, and returns its previous size
24
public class Main {
@FunctionalInterface
interface Action {
void run(String s);
}
public void action(Action action){
action.run("Hello");
}
public static void main(String[] args) {
new Main().action(
(String s) -> System.out.print("*" + s + "*")
);
}
}
25

OUTPUT: *Hello*
There is a generated method lambda$0 in the decompiled class

E:JAVA-8-EXAMPLESLAMBDA>javap -p Main
Compiled from "Main.java"
public class Main {
public Main();
public void action(Main$Action);
public static void main(java.lang.String[]);
private static void lambda$main$0(java.lang.String);
}

26
Method Reference
Sometimes a lambda expression does
nothing but calls an existing method.
In these cases it is clearer to refer
to that existing method by name.
Method reference is a lambda expression
for a method that already has a name.
Lets see an example....
27

© Unibet Group plc 2011
public class Person {
private Integer age;
public Person(Integer age) {
this.setAge(age);
}
public Integer getAge() {
return age;
}
private void setAge(Integer age) {
this.age = age;
}
public static int compareByAge(Person a, Person b) {
return a.getAge().compareTo(b.getAge());
}
public static List<Person> createRoster() {
List<Person> roster = new ArrayList<>();
roster.add(new Person(20));
roster.add(new Person(24));
roster.add(new Person(35));
return roster;
}
@Override
public String toString() { return "Person{ age=" + age + "}"; }
}

28
public class WithoutMethodReferenceTest {

Without Method Reference

public static void main(String[] args) {
List<Person> roster = Person.createRoster();
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
class PersonAgeComparator implements Comparator<Person> {
public int compare(Person a, Person b) {
return a.getAge().compareTo(b.getAge());
}
}
// Without method reference
Arrays.sort(rosterAsArray, new PersonAgeComparator());
for(int i=0; i<rosterAsArray.length; ++i){
System.out.println("" + rosterAsArray[i]);
}
}
}

29

OUTPUT
Person{age=20}
Person{age=24}
Person{age=35}
Ah ....
PersonAgeComparator implements
Comparator.
Comparator is a functional interface.
So lambda expression can be used
instead of defining and then creating a
new instance of a class that implements
30

Comparator<Person>.
With Lambda Expression
public class WithLambdaExpressionTest {
public static void main(String[] args) {
List<Person> roster = Person.createRoster();
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
// With lambda expression
Arrays.sort(rosterAsArray,
(Person a, Person b) -> {return a.getAge().compareTo(b.getAge());}
);
for(int i=0; i<rosterAsArray.length; ++i){
System.out.println("" + rosterAsArray[i]);
}
}
}

OUTPUT
Person{age=20}
Person{age=24}
Person{age=35}

31
However, this method to compare the ages of
two Person instances already exists as
Person.compareByAge
So we can invoke this method instead in the
body of the lambda expression:
Arrays.sort(rosterAsArray,
(a, b) -> Person.compareByAge(a, b) );

But we can do it more concisely using Method
Reference.
32
With Method Reference

public class MethodReferenceTest {
public static void main(String[] args) {
List<Person> roster = Person.createRoster();
Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);
// With method reference
Arrays.sort(rosterAsArray,

Person::compareByAge

);

for(int i=0; i<rosterAsArray.length; ++i){
System.out.println("" + rosterAsArray[i]);
}
}
}

OUTPUT
Person{age=20}
Person{age=24}
Person{age=35}

33
There are four kinds of Method
Reference
Reference to a static method
ContainingClass::staticMethodName
Reference to an instance method of a particular object
ContainingObject::instanceMethodName
Reference to an instance method of an arbitrary object
of a particular type
ContainingType::methodName
Reference to a constructor
ClassName::new
34
Examples
Reference to a static method

Person::compareByAge

35
Examples (cont.)
Reference to an instance method of a particular
object
class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
ComparisonProvider myCompProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myCompProvider::compareByName);
36
Examples (cont.)
Reference to an instance method of an
arbitrary object of a particular type

String[] stringArray = { "Barbara", "James", "Mary",
"John", "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase );

37
Examples (cont.)
Reference to a constructor
Set<Person> rosterSet =
transferElements(roster, HashSet::new );

38
java.util.function
Function<T, R>
R as output

Takes a T as input, returns an

Predicate<T> Takes a T as input, returns a
boolean as output
Consumer<T> Takes a T as input, performs some
action and doesn't return anything
Supplier<T> Does not take anything as input,
return a T
And many more --39
java.util.stream
Allows us to perform filter/map/reduce
-like operations with the collections
in Java 8.
List<Book> books = …
//sequential version
Stream<Book> bookStream = books.stream();
//parallel version
Stream<Book> parallelBookStream =
books.parallelStream();
40
Thank you.

More Related Content

What's hot

Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
SameerAhmed593310
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
Vladislav sidlyarevich
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 

What's hot (20)

Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
07 java collection
07 java collection07 java collection
07 java collection
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 

Viewers also liked

Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Trung Nguyen
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
Simon Ritter
 
Java 8
Java 8Java 8
Java 8
Raghda Salah
 
Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-api
Jini Lee
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
Ganesh Samarthyam
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
 
Java8
Java8Java8
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
Networking in java
Networking in javaNetworking in java
Networking in java
shravan kumar upadhayay
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Junit 4.0
Junit 4.0Junit 4.0
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
Craig Dickson
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 

Viewers also liked (20)

Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Java 8
Java 8Java 8
Java 8
 
Java8 javatime-api
Java8 javatime-apiJava8 javatime-api
Java8 javatime-api
 
Java8
Java8Java8
Java8
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java8
Java8Java8
Java8
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 

Similar to Major Java 8 features

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
Maýur Chourasiya
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
Sergii Maliarov
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
Henri Tremblay
 
SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8
Chaitanya Ganoo
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
Dian Aditya
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
ssuser7f90ae
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
Esther Lozano
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 

Similar to Major Java 8 features (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 

More from Sanjoy Kumar Roy

Arch CoP - Domain Driven Design.pptx
Arch CoP - Domain Driven Design.pptxArch CoP - Domain Driven Design.pptx
Arch CoP - Domain Driven Design.pptx
Sanjoy Kumar Roy
 
Visualizing Software Architecture Effectively in Service Description
Visualizing Software Architecture Effectively in Service DescriptionVisualizing Software Architecture Effectively in Service Description
Visualizing Software Architecture Effectively in Service Description
Sanjoy Kumar Roy
 
Hypermedia API and how to document it effectively
Hypermedia API and how to document it effectivelyHypermedia API and how to document it effectively
Hypermedia API and how to document it effectively
Sanjoy Kumar Roy
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
Sanjoy Kumar Roy
 
Transaction
TransactionTransaction
Transaction
Sanjoy Kumar Roy
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principles
Sanjoy Kumar Roy
 
Lessons learned in developing an agile architecture to reward our customers.
Lessons learned in developing an agile architecture to reward our customers.Lessons learned in developing an agile architecture to reward our customers.
Lessons learned in developing an agile architecture to reward our customers.
Sanjoy Kumar Roy
 
An introduction to G1 collector for busy developers
An introduction to G1 collector for busy developersAn introduction to G1 collector for busy developers
An introduction to G1 collector for busy developers
Sanjoy Kumar Roy
 

More from Sanjoy Kumar Roy (8)

Arch CoP - Domain Driven Design.pptx
Arch CoP - Domain Driven Design.pptxArch CoP - Domain Driven Design.pptx
Arch CoP - Domain Driven Design.pptx
 
Visualizing Software Architecture Effectively in Service Description
Visualizing Software Architecture Effectively in Service DescriptionVisualizing Software Architecture Effectively in Service Description
Visualizing Software Architecture Effectively in Service Description
 
Hypermedia API and how to document it effectively
Hypermedia API and how to document it effectivelyHypermedia API and how to document it effectively
Hypermedia API and how to document it effectively
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
Transaction
TransactionTransaction
Transaction
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principles
 
Lessons learned in developing an agile architecture to reward our customers.
Lessons learned in developing an agile architecture to reward our customers.Lessons learned in developing an agile architecture to reward our customers.
Lessons learned in developing an agile architecture to reward our customers.
 
An introduction to G1 collector for busy developers
An introduction to G1 collector for busy developersAn introduction to G1 collector for busy developers
An introduction to G1 collector for busy developers
 

Recently uploaded

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 

Recently uploaded (20)

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 

Major Java 8 features

  • 1. Major Java 8 Features Sanjoy Kumar Roy sanjoykr78@gmail.co m
  • 2. Agenda Interface Improvements Functional Interfaces Lambdas Method references java.util.function java.util.stream
  • 3. Interface Improvements Interfaces can now define static methods. For Example: naturalOrder method in java.util.Comparator public interface Comparator<T> { ……… public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() { return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE; } ………… } 3
  • 4. Interface Improvements (cont.) Interfaces can define default methods public interface A { default void foo(){ System.out.println("Calling A.foo()"); } } public class MyClass implements A { } MyClass clazz = new MyClass(); clazz.foo(); // Calling A.foo() 4
  • 5. Interface Improvements (cont.) Multiple inheritance? Interface A Interface B default void foo() default void foo() Class MyClass implements A, B 5
  • 6. Interface Improvements (cont.) public interface A { default void foo(){ System.out.println("Calling A.foo()"); } } CODE FAILS public interface B { default void foo(){ System.out.println("Calling A.foo()"); } } public class MyClass implements A, B { } 6
  • 7. Interface Improvements (cont.) This can be fixed : Overriding in implementation class public class MyClass implements A, B { default void foo(){ System.out.println("Calling from my class."); } } OR public class MyClass implements A, B { default void foo(){ A.super.foo(); Calling the default implementation of method } foo() from interface A } 7
  • 8. Interface Improvements (cont.) Another Example forEach method in java.lang.Iterable public default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } 8
  • 9. Interface Improvements (cont.) Why do we need default methods in Interface? List<Person> persons = asList( new Person("Joe"), new Person("Jim"), new Person("John")); persons.forEach(p -> p.setLastName("Doe")) 9
  • 10. Interface Improvements (cont.) Enhancing the behaviour of existing libraries (Collections) without breaking backwards compatibility. 10
  • 11. Functional Interface An interface is a functional interface if it defines exactly one abstract method. For Example: java.lang.Runnable is a functional interface. Because it has only one abstract method. @FunctionalInterface public interface Runnable { public abstract void run(); } 11
  • 12. Functional Interface (cont.) Functional interfaces are also called Single Abstract Method (SAM) interfaces. Anonymous Inner Classes can be created using these interfaces. public class MyAnonymousInnerClass { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(“Hello!"); }}).start(); } } 12
  • 13. Functional Interface (cont.) public class MyAnonymousInnerClass { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(“Hello!"); }}).start(); Unclear } Bit excessive } Cumbersome Lambda Expressions can help us 13
  • 14. How can lambda expression help us? But before that we need to see: Why are lambda expressions being added to Java? 14
  • 15. Most pressing reason is: Lambda expressions make the distribute processing of collections over multiple threads easier. 15
  • 16. How do we process lists and sets today ? Collection Iterator What is the issue? 16 Client Code Parallel Processing
  • 17. In Java 8 - Client Code CODE AS A DATA f Collection f 17 f f f
  • 18. Benefits of doing this:  Collections can now organise their iteration internally.  Responsibility for parallelisation is transferred from client code to library code. 18
  • 19. But client code needs a simple way of providing a function to the collection methods. Currently the standard way of doing this is by means of an anonymous class implementation of the appropriate interface. Using a lambda, however, the same effect can be achieved much more concisely. 19
  • 20. public class MyAnonymousInnerClass { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(“Hello!"); }}).start(); } } public class MyAnonymousInnerClass { public static void main(String[] args) { new Thread(() -> System.out.println(“Hello!") ).start(); } } 20
  • 21. Lambda Expression Lambda Expression (Project Lambda) is one of the most exciting feature of Java 8. Remember SAM type? In Java lambda expression is SAM type. Lambda expressions let us express instances of single-method classes more compactly. 21
  • 22. So what is lambda expression? In mathematics and computing generally, a lambda expression is a function. For some or all combinations of input values 22 It specifies An output value
  • 23. Lambda Syntax The basic syntax of lambda is either (parameters) -> expression or (parameters) -> { statements; } 23
  • 24. Some examples (int x, int y) -> x + y // takes two integers and returns their sum (x, y) -> x – y // takes two numbers and returns their difference () -> 42 // takes no values and returns 42 (String s) -> System.out.println(s) // takes a string, prints its value to the console, and returns nothing x -> 2 * x // takes a number and returns the result of doubling it c -> { int s = c.size(); c.clear(); return s; } // takes a collection, clears it, and returns its previous size 24
  • 25. public class Main { @FunctionalInterface interface Action { void run(String s); } public void action(Action action){ action.run("Hello"); } public static void main(String[] args) { new Main().action( (String s) -> System.out.print("*" + s + "*") ); } } 25 OUTPUT: *Hello*
  • 26. There is a generated method lambda$0 in the decompiled class E:JAVA-8-EXAMPLESLAMBDA>javap -p Main Compiled from "Main.java" public class Main { public Main(); public void action(Main$Action); public static void main(java.lang.String[]); private static void lambda$main$0(java.lang.String); } 26
  • 27. Method Reference Sometimes a lambda expression does nothing but calls an existing method. In these cases it is clearer to refer to that existing method by name. Method reference is a lambda expression for a method that already has a name. Lets see an example.... 27 © Unibet Group plc 2011
  • 28. public class Person { private Integer age; public Person(Integer age) { this.setAge(age); } public Integer getAge() { return age; } private void setAge(Integer age) { this.age = age; } public static int compareByAge(Person a, Person b) { return a.getAge().compareTo(b.getAge()); } public static List<Person> createRoster() { List<Person> roster = new ArrayList<>(); roster.add(new Person(20)); roster.add(new Person(24)); roster.add(new Person(35)); return roster; } @Override public String toString() { return "Person{ age=" + age + "}"; } } 28
  • 29. public class WithoutMethodReferenceTest { Without Method Reference public static void main(String[] args) { List<Person> roster = Person.createRoster(); Person[] rosterAsArray = roster.toArray(new Person[roster.size()]); class PersonAgeComparator implements Comparator<Person> { public int compare(Person a, Person b) { return a.getAge().compareTo(b.getAge()); } } // Without method reference Arrays.sort(rosterAsArray, new PersonAgeComparator()); for(int i=0; i<rosterAsArray.length; ++i){ System.out.println("" + rosterAsArray[i]); } } } 29 OUTPUT Person{age=20} Person{age=24} Person{age=35}
  • 30. Ah .... PersonAgeComparator implements Comparator. Comparator is a functional interface. So lambda expression can be used instead of defining and then creating a new instance of a class that implements 30 Comparator<Person>.
  • 31. With Lambda Expression public class WithLambdaExpressionTest { public static void main(String[] args) { List<Person> roster = Person.createRoster(); Person[] rosterAsArray = roster.toArray(new Person[roster.size()]); // With lambda expression Arrays.sort(rosterAsArray, (Person a, Person b) -> {return a.getAge().compareTo(b.getAge());} ); for(int i=0; i<rosterAsArray.length; ++i){ System.out.println("" + rosterAsArray[i]); } } } OUTPUT Person{age=20} Person{age=24} Person{age=35} 31
  • 32. However, this method to compare the ages of two Person instances already exists as Person.compareByAge So we can invoke this method instead in the body of the lambda expression: Arrays.sort(rosterAsArray, (a, b) -> Person.compareByAge(a, b) ); But we can do it more concisely using Method Reference. 32
  • 33. With Method Reference public class MethodReferenceTest { public static void main(String[] args) { List<Person> roster = Person.createRoster(); Person[] rosterAsArray = roster.toArray(new Person[roster.size()]); // With method reference Arrays.sort(rosterAsArray, Person::compareByAge ); for(int i=0; i<rosterAsArray.length; ++i){ System.out.println("" + rosterAsArray[i]); } } } OUTPUT Person{age=20} Person{age=24} Person{age=35} 33
  • 34. There are four kinds of Method Reference Reference to a static method ContainingClass::staticMethodName Reference to an instance method of a particular object ContainingObject::instanceMethodName Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName Reference to a constructor ClassName::new 34
  • 35. Examples Reference to a static method Person::compareByAge 35
  • 36. Examples (cont.) Reference to an instance method of a particular object class ComparisonProvider { public int compareByName(Person a, Person b) { return a.getName().compareTo(b.getName()); } public int compareByAge(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } } ComparisonProvider myCompProvider = new ComparisonProvider(); Arrays.sort(rosterAsArray, myCompProvider::compareByName); 36
  • 37. Examples (cont.) Reference to an instance method of an arbitrary object of a particular type String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" }; Arrays.sort(stringArray, String::compareToIgnoreCase ); 37
  • 38. Examples (cont.) Reference to a constructor Set<Person> rosterSet = transferElements(roster, HashSet::new ); 38
  • 39. java.util.function Function<T, R> R as output Takes a T as input, returns an Predicate<T> Takes a T as input, returns a boolean as output Consumer<T> Takes a T as input, performs some action and doesn't return anything Supplier<T> Does not take anything as input, return a T And many more --39
  • 40. java.util.stream Allows us to perform filter/map/reduce -like operations with the collections in Java 8. List<Book> books = … //sequential version Stream<Book> bookStream = books.stream(); //parallel version Stream<Book> parallelBookStream = books.parallelStream(); 40