Java 8 Bootcamp

19
Mohamed Ben Hassine Java / JEE Technical Lead Trainer [email protected] (+216) 52 633 220 www.linkedin.com/in/mohamedbnhassine Java 8 Bootcamp

Transcript of Java 8 Bootcamp

Page 1: Java 8 Bootcamp

Mohamed Ben HassineJava / JEE Technical LeadTrainer [email protected](+216) 52 633 220

www.linkedin.com/in/mohamedbnhassine

Java 8 Bootcamp

Page 2: Java 8 Bootcamp

Java 8 BootcampWhat you will Learn

• Get Started • Lambda Expressions• Java 8 Stream API• New Date and Time API• Nashorn: New JavaScript Engine• Miscellaneous

Page 3: Java 8 Bootcamp

LAMBDA EXPRESSION

Page 4: Java 8 Bootcamp

4

History of Java releases19

95JD

K In

trod

uctio

n

Janu

ary

1996

JD

K 1.

0“O

AK”

JDK

1.0

Dece

mbe

r 199

8 J2

SE 1

.2

Foun

datio

n of

JCJ

Swin

g , C

olle

ction

s

Febr

uary

200

2J2

SE 1

.4As

sert

, JA

XP ,I

Pv6

Regu

lar E

xpre

ssio

ns

February 1997JDK 1.1

Java Beans, RMI , JDBC, JIT

May 2000J2SE 1.3

HotSpot JVM , JNDI, Java Debugger

September 2004J2SE 5.0

Generics, Metadata, Concurrency, Static Import

September 2006Java SE 6

Java Compiler API ,Support JDBC 4.0 , JVM improvements

July 2011Java SE 7

Try-with-ResourcesStrings in switchNew IO API , Dynamic languages

March 2015Java SE 8

Project Lambda Streams API , Functional Interfaces ,Nashorn Engine ,New Date Time API , Annotations on Type 2017

Java SE 9Jshell Java REPL , Support HTTP 2.0 , G1 default Garbage Collector

Get Started

Page 5: Java 8 Bootcamp

5

Why Java 8 Now ?

Get Started

Revolution in Processing powerParallel multicores architecturesBig Data Applications

Code behaviorCode as data Functional programming Support

Enhance core librairiesInterface unlocking (concrete methods )Backward compatibility

Java / JavascriptJavaScript made great in Java 8

Page 6: Java 8 Bootcamp

6

Install and configure Java 8

Get Started

Page 7: Java 8 Bootcamp

7

Project Based Course

Get Started

Employee management Throughout the whole course , we will develop a java console app which offers suck key features :

Add manage employee Manage employees personal details , salaries and bonus Search employee by predefined criteria

Page 8: Java 8 Bootcamp

Lambda ExpressionsFirst Lambda Expression

Comparator<Employee> compLambda = ( emp1, emp2) -> {

int i = Integer.compare(emp1.getAge(), emp2.getAge());

if (i != 0) {

return i;} else {

i = Double.compare(emp1.getSalary(), emp2.getSalary());

if (i != 0)return i;}return i;};

Collections.sort(persons, compLambda);

Much Easier ! persons.sort(Comparator.comparing(Employee::getAge).thenComparing(Employee::getSalary));

Don’t worry about this code for now. ThisCourse will explain what it does and how you can develop

similar code!

Page 9: Java 8 Bootcamp

Lambda ExpressionsWhy Lambda Expression

Using anonymous classes for code behavior parameterization is verbose Programmers struggle with anonymous classes.(confusion “this”, no access to non-final local variables)

Convenient for new streams librarypersons.forEach(emp -> emp.setSalary(3000));

Solution :

Lambda let you represent a behavior or pass code in a concise way.Another way to write anonymous classes

Comparator<Employee> compLambda = ( emp1, emp2) -> { return emp1.getJobTitle().compareTo(emp2.getJobTitle()); }

Lambda Parameters

Arrow

Lambda Body

Page 10: Java 8 Bootcamp

Lambda ExpressionsHow to Write Lambda Expression

The simple way

More than One line of code

Runnable r = () -> {

for (int i = 0; i < 2016; i++) {System.out.println("Hello to your Java SE 8 Bootcamp 2016 !");

}};

More than One ArgumentComparator<Employee> compLambda = (Employee emp1, Employee emp2) -> {

return emp1.getJobTitle().compareTo(emp2.getJobTitle());

};

FileFilter filter = (File file) -> file.getName().endsWith("class");

Page 11: Java 8 Bootcamp

Lambda ExpressionsSo what is exactly Lambda Expression ?

Everything in Java has a type so what for Lambda ? :Lambda Expression is Functional Interface ( new Java 8 concept , Interface with one abstract Method..example Runnable , Comparator interfaces known prior to Java SE8 as Single Abstract Method Interface).

Where to use A Lambda Expression ?In each case it could be assigned to a variable of Type Functional Interface

Runnable r = () -> System.out.println("Hello to your Java SE 8 Bootcamp 2016 !");;

Lambda Expression

Page 12: Java 8 Bootcamp

Lambda ExpressionsFunctional Interface

An Interface with only one abstract method

Example :

public interface Runnable {

public abstract void run();}

@FunctionalInterfacepublic interface SimpleInterface {

public void doSomeJob() ;

}

Define Java SE8 Functional Interface

Page 13: Java 8 Bootcamp

Lambda ExpressionsPredefined Functional Interface in JAVA SE8

New Java Package : java.util.function

Divided into 4 categories :

Supplier Consumer Predicate /** @since 1.8 */@FunctionalInterfacepublic interface Supplier<T> {

/** * Gets a result. * * @return a result */ T get();}

Function /** @since 1.8 */@FunctionalInterfacepublic interface Consumer<T> {

/*** @param t the input argument */ void accept(T t);}

/** @since 1.8 */@FunctionalInterfacepublic interface Predicate<T> {

/** * Evaluates this predicate on the given argument. */boolean test(T t);}

/** @since 1.8 */@FunctionalInterfacepublic interface Function<T, R> {

/** * Applies this function to the given argument.*/ R apply(T t);}

Page 14: Java 8 Bootcamp

Lambda ExpressionsMethod Reference

Simply : An other way to write Lambda Expression

Comparator<Employee> compLambda = (Employee emp1, Employee emp2) -> {

return Double.compare(emp1.getSalary(), emp2.getSalary()) ;

}

;

Comparator<Employee> compLambdaRef = Comparator.comparing(Employee::getSalary);

– Replace(args) -> ClassName.staticMethodName(args)– withClassName::staticMethodName

Page 15: Java 8 Bootcamp

Lambda ExpressionsSo how to process Data with this Lambda ?

List<Employee> persons = new ArrayList<>();

persons.add(new Employee("Mohamed", 30, 2500, new Date(), true, "Java / JEE TL"));

persons.add(new Employee("Ferdaous", 24, 1900, new Date(), false, "IT Consultant"));

// Prior to Java SE 8

for (Employee employee : persons) { System.out.println(employee) ;}

Using Lambda Expression

// Traverse collection with Lambda Expression

persons.forEach(emp -> System.out.println(emp));

// More concise syntax with Method Reference

persons.forEach(System.out::println);

Where does this method come from ? All interface implementations of Iterable should be refactored !.. Response Next episode ..

Page 16: Java 8 Bootcamp

Lambda ExpressionsDefault Method

In Java 8 a method can be implemented in an interface.

New Java 8 Concept for backward compatibility

Allow to add methods to an existing interface long after it has been released without breaking the interface

Interface

void newMethod()

Class

implements

Compilation Error must implement newMethod

Solution to not modify sub class

Interface

default void newMethod() {

Code here….}

Does not break any sub class implementing this Interface

Default Method could be overridden in interface implementation

Page 17: Java 8 Bootcamp

Lambda ExpressionsInterface Static Method

Similar to default methods except that it is not possible to override them in the implementation classes providing security.Interface static methods are good for providing utility methods.

Interface

void newMethod()

Class

implements

Compilation Error must implement newMethod

Solution to not modify sub class

Interface

Static void newMethod() {

Code here….}

Does not break any sub class implementing this Interface

Page 18: Java 8 Bootcamp

JAVA 8 STREAM API

Page 19: Java 8 Bootcamp

JAVA 8 Stream APIWhat’s Stream API

Coming Soon