SlideShare a Scribd company logo
1 of 43
Java 8 New Features
and enhancements
Aniket Thakur
Interface Basics
• What we know so far
• What is an interface?
• Variables in an interface?
• Methods in an interface?
• Interface Vrs Abstract class?
interface A
{
void printEmployeeNames(String division);
}
interface B
{
void printEmployeeNames(String division);
}
class AB implements A,B
{
@Override
public void printEmployeeNames(String division)
{
//print employee names based on division
}
}
public class HelloWorld
{
public static void main(String args[])
{
new AB().printEmployeeNames(”Security");
}
}
Will this work?
Java 8 changes in interface
• Static Methods are allowed
• Eg.
interface A
{
static void printEmployeeNames(String division)
{
//print employee names based on division
}
}
Default Methods
• Provide default implementation of methods defined in an
interface.
• Don’t have to make changes in all concrete subclasses
implementing the interface
Eg –
interface A {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
interface A {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
interface B {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
class AB implements A,B {
}
//make an instance of AB and call printEmployeeNames
Will this work?
interface A {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
interface B {
default void printEmployeeNames(String division) {
//print employee names based on division
}
}
class AB implements A,B {
@Override
public void printEmployeeNames(String division) {
A.super.printEmployeeNames(division);//whats this?
//print employee names based on division
}
}
//make an instance of AB and call printEmployeeNames
Will this work?
Final local variable(effectively
final)
public void foo() {
final String x = "hello";
String y = "there";
Runnable runnable = new Runnable() {
@Override public void run() {
System.out.println(x);
System.out.println(y);
}
};
runnable.run();
}
Changes in HashMap
• Using Balanced trees instead of Linked List
• Improves worst case performance from O(n) to O(log n).
• Implementation in -
• java.util.HashMap,
• java.util.LinkedHashMap and
• java.util.concurrent.ConcurrentHashMap.
Functional Interfaces
• Interface with just one abstract method.
Eg. –
interface MyInterface {
int getAge();
}
• How about?
interface A {
boolean equals(Object obj);
int getAge();
}
How about?
interface A {
default void printEmployeeNames(String division) {}
static void newMethod(){}
int getAge();
}
• OR
interface A {
public boolean equals(Object obj);
default void printEmployeeNames(String division) {}
static void newMethod(){}
int getAge();
int getNewAge();
}
Seen before?
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
OR
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
About Functional interfaces
• Any public method defined by Object, any default methods or
any static methods do not affect the functional status of an
functional interface. As long as it has just one abstract
method.
• Questions?
Common functional interfaces
• Part of java.util.function
• https://docs.oracle.com/javase/8/docs/api/java/util/function/
package-summary.html
• The convention used here us generic type T for type
parameter, for second type parameter the next letter U and
for a distinct return type R is used as the generic type.
Predicate
• Takes a single paramter of any type and returns a boolean
@FunctionalInterface // what’s this?
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the
predicate,
* otherwise {@code false}
*/
boolean test(T t);
//other methods
}
Consumer
• Takes a single paramter of any type and has a void return type
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
Supplier
• Does not take any parameter and returns any type
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
UnaryOperator
• Takes a single parameter of any type and returns of same type
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
Lambda Expressions
• Lambda expression implements the abstract method in a
functional interface.
• Kind of anonymous class. Also called closures.
Types
• Expression Lamdas
• Block Lambdas
interface MyInterface {
boolean isAllowedAge(int currentAge, int minAge);
}
MyInterface myInterface = (n,m) -> n>=m;//expression
System.out.println(myInterface.isAllowedAge(4,5));
MyInterface myInterface = (n,m) -> { //block
int minAge = m;
if (n >= minAge )
return true;
else
return false;
}
System.out.println(myInterface.isAllowedAge(4,5));
Similarities n Difference
• Block lambdas must have return statements unlike expression ones
where RHS is the return value.
• We can omit specifying argument types. It is automatically inferred
from Functional interface.
• You can have local variables, loops , case statement in you block.
• Same access rules as inner classes.
• Same goes for exception handling. You lambda expression can throw
checked exception but so must you abstract method (compatibility).
• Eg.
Runnable myRunner= () ->{
System.out.println("I am running");
};
Power Of Lambda expression
• What makes Lambda expressions so special?
• Deferred execution
• You can now send executable code as method argument.
• More later 
Say hello to Generics
• lambda expression themselves cannot have generics but the functional interface that
corresponds to a lambda expression can have generics.
Eg.
public class HelloWorld {
public static void main(String args[]) {
MyInterface<String> myStringInterface = (input) -> "Hello " + input;
MyInterface<Integer> myIntInterface = (input) -> 10 + input;
System.out.println("String based lambda exp : " + myStringInterface.myFunc(”I am
Groot"));
System.out.println("Integer based labmda exp : " + myIntInterface.myFunc(14));
}
}
interface MyInterface<T> {
T myFunc(T t);
}
Questions?
Revisiting common functional
interfaces
• Predicate :
Predicate<String> emptyPredicate = x -> x.isEmpty();
System.out.println(emptyPredicate.test(""));
System.out.println(emptyPredicate.test("abc"));
• Consumer :
Consumer<String> printFunc = x -> System.out.println(x);
printFunc.accept("Hello World!");
• Supplier :
Supplier<String> strSupplier = () -> "SOME_CONSTANT";
System.out.println(strSupplier.get());
• UnaryOperator
UnaryOperator<String> prefixOp = (name) -> "Mr. " + name;
System.out.println(prefixOp.apply("Aniket"));
Method references
• Because Lambda expressions were not enough 
• 4 types –
• Reference to a static method
• Reference to a constructor
• Reference to an instance method of an arbitrary object of a
particular type
• Reference to an instance method of a particular object
1. Reference to a static
method
List<String> platforms=
Arrays.asList(“Android”,”iOS”,”Windows”,”IDontCare”);
Consumer<List<String>> methodRef1 = Collections::sort;
methodRef1.accept(platforms);
System.out.println(platforms);
• Equivalent Lambda :
Consumer<List<String>> lambdaRef1 = l -> Collections.sort(l);
2. Reference to a constructor
Supplier<ArrayList<String>> methodRef2 = ArrayList::new;
List<String> newEmployeeNameList = methodRef2.get();
newEmployeeNameList.add(”Intern1");
newEmployeeNameList.add(”Intern2");
System.out.println(newEmployeeNameList);
• Equivalent Lambda :
Supplier<ArrayList> lambdaRef2 = () -> new ArrayList();
• Advice : Try not to look at LHS for functional interface types
and try to guess what kind of interface it is. Coz later we will
directly use it in method arguments. More good stuff to follow

3. Referenceto an instance methodof an
arbitraryobjectof a particulartype
Predicate<String> methodRef3 = String::isEmpty;
String emtptyString = "";
System.out.println(methodRef3.test(emtptyString));
• Equivalent Lambda :
Predicate<String> lambdaRef3 = s -> s.isEmpty();
4. Referenceto an instance methodof a
particularobject
String myName = "Aniket";
Predicate<String> methodRef4 = myName::contains;
System.out.println(methodRef4.test("ike"));
• Equivalent Lambda :
Predicate<String> lambda2 = s -> s.contains(“ike”);
Questions?
Stream API
• Basically sequence of data on which you can operate.
• Three essential parts –
• Source
• Think of this as data set used to generate a stream. Depending on
this a stream can be
• Finite Or
• Infinite
• Intermediate operations
• These operations you can perform on the data set to filter our or
process your data. You can use as many as you desire. One
intermediate operation will give you stream back so that you can
perform additional intermediate operations on it.
• Terminal operations
• These operations produce final results. Only one terminal operation
is allowed per stream.
Generating a Stream
Stream<String> emptyStream =
Stream.empty(); Stream<Integer> singleElementStream =
Stream.of(1); Stream<Integer> streamFromArray =
Stream.of(1,2,3,4);
List<String> listForStream =
Arrays.asList("ABC","PQR","XYZ"); Stream<String>
streamFromList = listForStream.stream(); //most helpful
Stream<Double> randomInfiniteStream =
Stream.generate(Math::random); // what’s this?
Stream<Integer> sequencedInfiniteStream = Stream.iterate(1, n
-> n+1);//what’s this?
Operations
• Common intermediate operations :
• filter()
• distinct()
• limit() and skip()
• map()
• sorted()
• peek()
• Common terminal operations :
• allMatch()/anyMatch()/noneMatch()
• collect()
• count()
• findAny()/findFirst()
• forEach()
• min()/max()
• reduce()
None of these affect the underlying data set (Unless you do something to
change it)
Terminal operations
Examples!
• How about printing a Stream?
List<String> listForStream =
Arrays.asList("ABC","PQR","XYZ"); Stream<String>
streamFromList = listForStream.stream();
//printing using forEach terminal
operation streamFromList.forEach(System.out::println);
//recreate stream as stream once operated on is
invalid streamFromList = listForStream.stream();
//printing using peek intermediate
operation streamFromList.peek(System.out::println).count()
; streamFromList = listForStream.stream();
//printing using collect terminal
operation System.out.println(streamFromList.collect(Collect
ors.toList()));
Some more…
List<String> listForStream = Arrays.asList(”India", ”USA",
”Russia", ”Iran", ”Italy", ”Iraq", ”Bhutan");
Stream<String> streamFromList = listForStream.stream();
streamFromList
.filter(x -> x.startsWith(“I"))
.sorted()
.limit(3)
.forEach(System.out::println);
N more…
Stream.iterate(1, n -> n+1)
.filter(x -> x%5==0)
.limit(5)
.forEach(System.out::println);
Stream.iterate(1, n -> n+1)
.filter(x -> x%5==0)
.peek(System.out::println)
.limit(5)
.forEach(System.out::println);
java.util.ConcurrentModificationException
• Same as iterator do not modify the underlying collection while
processing it’s stream. Else you will get -
java.util.ConcurrentModificationException
• Eg.
List<String> listForStream = new
ArrayList<>(Arrays.asList("ABC","PQR","XYZ"));
Stream<String> streamFromList =
listForStream.stream(); streamFromList.forEach(elm ->
listForStream.remove(elm));//boom
System.out.println(listForStream);
Last but not the least
• Other topics you can cover on your own
1. Optional class and it’s usage (Specially in Spring MVC)
2. New NIO.2 APIs – Path, Files, walking dir etc.
3. Stream for primitives – IntStream, LongStream, DoubleStream
etc
4. Parallel stream – multi threading involved
5. ExecutorService – Callable , Runnable are functional interfaces
6. New Date/Time API
Java SE 8 OCP Programmer
• If you already have Java 7 certification :
• http://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:
1Z0-810
• If you have Java 6 or prior certification :
• https://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:
1Z0-813
• First timers :
• You need to give associate level exam first :
• https://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-
808
• Then you can give professional once :
• https://education.oracle.com/pls/web_prod-plq-
dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-
809
Java 8 new features

More Related Content

What's hot

Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8Dinesh Pathak
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 

What's hot (20)

Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Java 8
Java 8Java 8
Java 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 

Viewers also liked

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 8Simon Ritter
 
Java 8 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesWSO2
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj Bhusare
 
Symbian OS With ARM Processor
Symbian OS With ARM ProcessorSymbian OS With ARM Processor
Symbian OS With ARM Processoralok3089
 
Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2rusersla
 
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 OverviewEclipse Day India
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuturekoji lin
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
2013 ARM Student Design Competition @RIT
2013 ARM Student Design Competition @RIT 2013 ARM Student Design Competition @RIT
2013 ARM Student Design Competition @RIT Antonio Mondragon
 
4th ARM Developer Day Presentation
4th ARM Developer Day Presentation4th ARM Developer Day Presentation
4th ARM Developer Day PresentationAntonio Mondragon
 
4th ARM Developer Day Presenters info
4th ARM Developer Day Presenters info4th ARM Developer Day Presenters info
4th ARM Developer Day Presenters infoAntonio Mondragon
 

Viewers also liked (20)

ARM Processor
ARM ProcessorARM Processor
ARM Processor
 
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 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Symbian OS With ARM Processor
Symbian OS With ARM ProcessorSymbian OS With ARM Processor
Symbian OS With ARM Processor
 
Jvm fundamentals
Jvm fundamentalsJvm fundamentals
Jvm fundamentals
 
Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2
 
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
 
Pub med
Pub medPub med
Pub med
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
 
Growth Hackers of Vienna MeetUp #1 Jan
Growth Hackers of Vienna MeetUp #1 JanGrowth Hackers of Vienna MeetUp #1 Jan
Growth Hackers of Vienna MeetUp #1 Jan
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Arm rit design_comp 2014
Arm rit design_comp 2014Arm rit design_comp 2014
Arm rit design_comp 2014
 
2013 ARM Student Design Competition @RIT
2013 ARM Student Design Competition @RIT 2013 ARM Student Design Competition @RIT
2013 ARM Student Design Competition @RIT
 
4th ARM Developer Day Presentation
4th ARM Developer Day Presentation4th ARM Developer Day Presentation
4th ARM Developer Day Presentation
 
4th ARM Developer Day Presenters info
4th ARM Developer Day Presenters info4th ARM Developer Day Presenters info
4th ARM Developer Day Presenters info
 
Los jaliles pesados
Los jaliles pesadosLos jaliles pesados
Los jaliles pesados
 
Exp w21
Exp w21Exp w21
Exp w21
 

Similar to Java 8 new features

New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
What's new in c# 8.0
What's new in c# 8.0What's new in c# 8.0
What's new in c# 8.0Moaid Hathot
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
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 InterfacesGanesh Samarthyam
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much moreAlin Pandichi
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8Roland Mast
 

Similar to Java 8 new features (20)

Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
02basics
02basics02basics
02basics
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java 8
Java 8Java 8
Java 8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
What's new in c# 8.0
What's new in c# 8.0What's new in c# 8.0
What's new in c# 8.0
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
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
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
 

Recently uploaded

Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 

Recently uploaded (20)

Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 

Java 8 new features

  • 1. Java 8 New Features and enhancements Aniket Thakur
  • 2. Interface Basics • What we know so far • What is an interface? • Variables in an interface? • Methods in an interface? • Interface Vrs Abstract class?
  • 3. interface A { void printEmployeeNames(String division); } interface B { void printEmployeeNames(String division); } class AB implements A,B { @Override public void printEmployeeNames(String division) { //print employee names based on division } } public class HelloWorld { public static void main(String args[]) { new AB().printEmployeeNames(”Security"); } } Will this work?
  • 4. Java 8 changes in interface • Static Methods are allowed • Eg. interface A { static void printEmployeeNames(String division) { //print employee names based on division } }
  • 5. Default Methods • Provide default implementation of methods defined in an interface. • Don’t have to make changes in all concrete subclasses implementing the interface Eg – interface A { default void printEmployeeNames(String division) { //print employee names based on division } }
  • 6. interface A { default void printEmployeeNames(String division) { //print employee names based on division } } interface B { default void printEmployeeNames(String division) { //print employee names based on division } } class AB implements A,B { } //make an instance of AB and call printEmployeeNames Will this work?
  • 7. interface A { default void printEmployeeNames(String division) { //print employee names based on division } } interface B { default void printEmployeeNames(String division) { //print employee names based on division } } class AB implements A,B { @Override public void printEmployeeNames(String division) { A.super.printEmployeeNames(division);//whats this? //print employee names based on division } } //make an instance of AB and call printEmployeeNames Will this work?
  • 8. Final local variable(effectively final) public void foo() { final String x = "hello"; String y = "there"; Runnable runnable = new Runnable() { @Override public void run() { System.out.println(x); System.out.println(y); } }; runnable.run(); }
  • 9. Changes in HashMap • Using Balanced trees instead of Linked List • Improves worst case performance from O(n) to O(log n). • Implementation in - • java.util.HashMap, • java.util.LinkedHashMap and • java.util.concurrent.ConcurrentHashMap.
  • 10. Functional Interfaces • Interface with just one abstract method. Eg. – interface MyInterface { int getAge(); } • How about? interface A { boolean equals(Object obj); int getAge(); }
  • 11. How about? interface A { default void printEmployeeNames(String division) {} static void newMethod(){} int getAge(); } • OR interface A { public boolean equals(Object obj); default void printEmployeeNames(String division) {} static void newMethod(){} int getAge(); int getNewAge(); }
  • 12. Seen before? @FunctionalInterface public interface Runnable { public abstract void run(); } OR @FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); }
  • 13. About Functional interfaces • Any public method defined by Object, any default methods or any static methods do not affect the functional status of an functional interface. As long as it has just one abstract method. • Questions?
  • 14. Common functional interfaces • Part of java.util.function • https://docs.oracle.com/javase/8/docs/api/java/util/function/ package-summary.html • The convention used here us generic type T for type parameter, for second type parameter the next letter U and for a distinct return type R is used as the generic type.
  • 15. Predicate • Takes a single paramter of any type and returns a boolean @FunctionalInterface // what’s this? public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t); //other methods }
  • 16. Consumer • Takes a single paramter of any type and has a void return type @FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); }
  • 17. Supplier • Does not take any parameter and returns any type @FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
  • 18. UnaryOperator • Takes a single parameter of any type and returns of same type @FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t); }
  • 19.
  • 20. Lambda Expressions • Lambda expression implements the abstract method in a functional interface. • Kind of anonymous class. Also called closures.
  • 21. Types • Expression Lamdas • Block Lambdas interface MyInterface { boolean isAllowedAge(int currentAge, int minAge); } MyInterface myInterface = (n,m) -> n>=m;//expression System.out.println(myInterface.isAllowedAge(4,5)); MyInterface myInterface = (n,m) -> { //block int minAge = m; if (n >= minAge ) return true; else return false; } System.out.println(myInterface.isAllowedAge(4,5));
  • 22. Similarities n Difference • Block lambdas must have return statements unlike expression ones where RHS is the return value. • We can omit specifying argument types. It is automatically inferred from Functional interface. • You can have local variables, loops , case statement in you block. • Same access rules as inner classes. • Same goes for exception handling. You lambda expression can throw checked exception but so must you abstract method (compatibility). • Eg. Runnable myRunner= () ->{ System.out.println("I am running"); };
  • 23. Power Of Lambda expression • What makes Lambda expressions so special? • Deferred execution • You can now send executable code as method argument. • More later 
  • 24. Say hello to Generics • lambda expression themselves cannot have generics but the functional interface that corresponds to a lambda expression can have generics. Eg. public class HelloWorld { public static void main(String args[]) { MyInterface<String> myStringInterface = (input) -> "Hello " + input; MyInterface<Integer> myIntInterface = (input) -> 10 + input; System.out.println("String based lambda exp : " + myStringInterface.myFunc(”I am Groot")); System.out.println("Integer based labmda exp : " + myIntInterface.myFunc(14)); } } interface MyInterface<T> { T myFunc(T t); }
  • 26. Revisiting common functional interfaces • Predicate : Predicate<String> emptyPredicate = x -> x.isEmpty(); System.out.println(emptyPredicate.test("")); System.out.println(emptyPredicate.test("abc")); • Consumer : Consumer<String> printFunc = x -> System.out.println(x); printFunc.accept("Hello World!"); • Supplier : Supplier<String> strSupplier = () -> "SOME_CONSTANT"; System.out.println(strSupplier.get()); • UnaryOperator UnaryOperator<String> prefixOp = (name) -> "Mr. " + name; System.out.println(prefixOp.apply("Aniket"));
  • 27. Method references • Because Lambda expressions were not enough  • 4 types – • Reference to a static method • Reference to a constructor • Reference to an instance method of an arbitrary object of a particular type • Reference to an instance method of a particular object
  • 28. 1. Reference to a static method List<String> platforms= Arrays.asList(“Android”,”iOS”,”Windows”,”IDontCare”); Consumer<List<String>> methodRef1 = Collections::sort; methodRef1.accept(platforms); System.out.println(platforms); • Equivalent Lambda : Consumer<List<String>> lambdaRef1 = l -> Collections.sort(l);
  • 29. 2. Reference to a constructor Supplier<ArrayList<String>> methodRef2 = ArrayList::new; List<String> newEmployeeNameList = methodRef2.get(); newEmployeeNameList.add(”Intern1"); newEmployeeNameList.add(”Intern2"); System.out.println(newEmployeeNameList); • Equivalent Lambda : Supplier<ArrayList> lambdaRef2 = () -> new ArrayList(); • Advice : Try not to look at LHS for functional interface types and try to guess what kind of interface it is. Coz later we will directly use it in method arguments. More good stuff to follow 
  • 30. 3. Referenceto an instance methodof an arbitraryobjectof a particulartype Predicate<String> methodRef3 = String::isEmpty; String emtptyString = ""; System.out.println(methodRef3.test(emtptyString)); • Equivalent Lambda : Predicate<String> lambdaRef3 = s -> s.isEmpty();
  • 31. 4. Referenceto an instance methodof a particularobject String myName = "Aniket"; Predicate<String> methodRef4 = myName::contains; System.out.println(methodRef4.test("ike")); • Equivalent Lambda : Predicate<String> lambda2 = s -> s.contains(“ike”);
  • 33. Stream API • Basically sequence of data on which you can operate. • Three essential parts – • Source • Think of this as data set used to generate a stream. Depending on this a stream can be • Finite Or • Infinite • Intermediate operations • These operations you can perform on the data set to filter our or process your data. You can use as many as you desire. One intermediate operation will give you stream back so that you can perform additional intermediate operations on it. • Terminal operations • These operations produce final results. Only one terminal operation is allowed per stream.
  • 34. Generating a Stream Stream<String> emptyStream = Stream.empty(); Stream<Integer> singleElementStream = Stream.of(1); Stream<Integer> streamFromArray = Stream.of(1,2,3,4); List<String> listForStream = Arrays.asList("ABC","PQR","XYZ"); Stream<String> streamFromList = listForStream.stream(); //most helpful Stream<Double> randomInfiniteStream = Stream.generate(Math::random); // what’s this? Stream<Integer> sequencedInfiniteStream = Stream.iterate(1, n -> n+1);//what’s this?
  • 35. Operations • Common intermediate operations : • filter() • distinct() • limit() and skip() • map() • sorted() • peek() • Common terminal operations : • allMatch()/anyMatch()/noneMatch() • collect() • count() • findAny()/findFirst() • forEach() • min()/max() • reduce() None of these affect the underlying data set (Unless you do something to change it)
  • 37. Examples! • How about printing a Stream? List<String> listForStream = Arrays.asList("ABC","PQR","XYZ"); Stream<String> streamFromList = listForStream.stream(); //printing using forEach terminal operation streamFromList.forEach(System.out::println); //recreate stream as stream once operated on is invalid streamFromList = listForStream.stream(); //printing using peek intermediate operation streamFromList.peek(System.out::println).count() ; streamFromList = listForStream.stream(); //printing using collect terminal operation System.out.println(streamFromList.collect(Collect ors.toList()));
  • 38. Some more… List<String> listForStream = Arrays.asList(”India", ”USA", ”Russia", ”Iran", ”Italy", ”Iraq", ”Bhutan"); Stream<String> streamFromList = listForStream.stream(); streamFromList .filter(x -> x.startsWith(“I")) .sorted() .limit(3) .forEach(System.out::println);
  • 39. N more… Stream.iterate(1, n -> n+1) .filter(x -> x%5==0) .limit(5) .forEach(System.out::println); Stream.iterate(1, n -> n+1) .filter(x -> x%5==0) .peek(System.out::println) .limit(5) .forEach(System.out::println);
  • 40. java.util.ConcurrentModificationException • Same as iterator do not modify the underlying collection while processing it’s stream. Else you will get - java.util.ConcurrentModificationException • Eg. List<String> listForStream = new ArrayList<>(Arrays.asList("ABC","PQR","XYZ")); Stream<String> streamFromList = listForStream.stream(); streamFromList.forEach(elm -> listForStream.remove(elm));//boom System.out.println(listForStream);
  • 41. Last but not the least • Other topics you can cover on your own 1. Optional class and it’s usage (Specially in Spring MVC) 2. New NIO.2 APIs – Path, Files, walking dir etc. 3. Stream for primitives – IntStream, LongStream, DoubleStream etc 4. Parallel stream – multi threading involved 5. ExecutorService – Callable , Runnable are functional interfaces 6. New Date/Time API
  • 42. Java SE 8 OCP Programmer • If you already have Java 7 certification : • http://education.oracle.com/pls/web_prod-plq- dad/db_pages.getpage?page_id=5001&get_params=p_exam_id: 1Z0-810 • If you have Java 6 or prior certification : • https://education.oracle.com/pls/web_prod-plq- dad/db_pages.getpage?page_id=5001&get_params=p_exam_id: 1Z0-813 • First timers : • You need to give associate level exam first : • https://education.oracle.com/pls/web_prod-plq- dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0- 808 • Then you can give professional once : • https://education.oracle.com/pls/web_prod-plq- dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0- 809