introduction to new features in java 8
TRANSCRIPT
![Page 1: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/1.jpg)
Introduction toIntroduction toNew Features inNew Features in
Java 8Java 8Raffi Khatchadourian
Department of Computer Systems TechnologyNew York City College of Technology
City University of New YorkComputer Systems Technology Colloquium
March 26, 2015Based on slides by Duarte Duarte, Eduardo Martins, Miguel Marques and
Ruben Cordeiro and Horstmann, Cay S. (2014-01-10). Java SE8 for theReally Impatient: A Short Course on the Basics (Java Series). Pearson
Education.
![Page 2: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/2.jpg)
Demonstration code at: .http://github.com/khatchad/java8-demo
![Page 3: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/3.jpg)
Some HistorySome History
Java was invented in the 90's as an Object-Oriented language.Largest change was in ~2005 with Java 5.
Generics.Enhanced for loops.Annotations.Type-safe enumerations.Concurrency enhancements (AtomicInteger).
![Page 4: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/4.jpg)
Java 8 is MassiveJava 8 is Massive
10 years later, Java 8 is packed with new features.Core changes are to incorporate functional language features.We can't cover everything today.Will focus on some of the more distributive features.
![Page 5: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/5.jpg)
Functional LanguagesFunctional Languages
Declarative ("what not how").The only state is held in parameters.Traditionally popular in academia and AI.Well-suited for event-driven/concurrent ("reactive") programs.
![Page 6: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/6.jpg)
Lambda ExpressionsLambda Expressions
A block of code that you can pass around so it can beexecuted later, once or multiple times.
Anonymous methods.Reduce verbosity caused by anonymous classes.
![Page 7: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/7.jpg)
How are they different from Java methods?
![Page 8: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/8.jpg)
LambdasLambdas(int x, int y) -> x + y
() -> 42
(String s) -> {System.out.println(s);}
![Page 9: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/9.jpg)
LambdasLambdasExamplesExamples
BeforeBefore
Button btn = new Button();final PrintStream pStream = ...;btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { pStream.println("Button Clicked!"); }});
AfterAfter
Button btn = new Button();final PrintStream pStream = ...;btn.setOnAction(e -> pStream.println("Button Clicked!"));
![Page 10: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/10.jpg)
LambdasLambdasExamplesExamples
List<String> strs = ...;Collections.sort(strs, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
new Thread(() -> { connectToService(); sendNotification();}).start();
![Page 11: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/11.jpg)
Functional InterfacesFunctional InterfacesSingle Abstract Method Type
![Page 12: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/12.jpg)
Functional InterfacesFunctional InterfacesExampleExample
@FunctionalInterfacepublic interface Runnable { public void run();}
Runnable r = () -> System.out.println("Hello World!");
![Page 13: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/13.jpg)
java.util.functionjava.util.functionPredicate<T> - a boolean-valued property of an objectConsumer<T> - an action to be performed on an objectFunction<T,R> - a function transforming a T to a RSupplier<T> - provide an instance of a T (such as a factory)UnaryOperator<T> - a function from T to TBinaryOperator<T> - a function from (T,T) to T
![Page 14: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/14.jpg)
Method ReferencesMethod ReferencesTreating an existing method as an instance of a
Functional Interface
![Page 15: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/15.jpg)
Method ReferencesMethod ReferencesExamplesExamples
class Person { private String name; private int age;
public int getAge() {return this.age;} public String getName() {return this.name;}}
Person[] people = ...;Comparator<Person> byName = Comparator.comparing(Person::getName);Arrays.sort(people, byName);
![Page 16: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/16.jpg)
Method ReferencesMethod ReferencesKinds of method referencesKinds of method references
A static method (ClassName::methName)An instance method of a particular object(instanceRef::methName)A super method of a particular object (super::methName)An instance method of an arbitrary object of a particular type(ClassName::methName)A class constructor reference (ClassName::new)An array constructor reference (TypeName[]::new)
![Page 17: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/17.jpg)
Method ReferencesMethod ReferencesMore ExamplesMore Examples
Consumer<Integer> b1 = System::exit;Consumer<String[]> b2 = Arrays::sort;Consumer<String> b3 = MyProgram::main;Runnable r = MyProgram::main;
![Page 18: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/18.jpg)
Default MethodsDefault MethodsAdd default behaviours to interfaces
![Page 19: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/19.jpg)
Why default methods?Why default methods?Java 8 has lambda expressions. We want to start using them:
List<?> list = ...list.forEach(...); // lambda code goes here
![Page 20: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/20.jpg)
There's a problemThere's a problemThe forEach method isn’t declared by java.util.List nor thejava.util.Collection interface because doing so would break
existing implementations.
![Page 21: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/21.jpg)
Default MethodsDefault MethodsWe have lambdas, but we can't force new behaviours into the current
libraries.Solution: default methods.
![Page 22: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/22.jpg)
Default MethodsDefault MethodsTraditionally, interfaces can't have method definitions (justdeclarations).Default methods supply default implementations of interfacemethods.
![Page 23: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/23.jpg)
ExamplesExamples
![Page 24: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/24.jpg)
Example 1Example 1BasicsBasics
![Page 25: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/25.jpg)
public interface A {
default void foo() { System.out.println("Calling A.foo()"); }}
public class Clazz implements A {}
![Page 26: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/26.jpg)
Client codeClient code
Clazz clazz = new Clazz();clazz.foo();
OutputOutput
"Calling A.foo()"
![Page 27: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/27.jpg)
Example 2Example 2Getting messyGetting messy
![Page 28: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/28.jpg)
public interface A {
default void foo(){ System.out.println("Calling A.foo()"); }}
public interface B {
default void foo(){ System.out.println("Calling B.foo()"); }
}
public class Clazz implements A, B {}
Does this code compile?
![Page 29: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/29.jpg)
Of course not (Java is not C++)!
class Clazz inherits defaults for foo() from both typesA and B
How do we fix it?
![Page 30: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/30.jpg)
Option A:public class Clazz implements A, B { public void foo(){/* ... */}}
We resolve it manually by overriding the conflicting method.Option B:
public class Clazz implements A, B { public void foo(){ A.super.foo(); // or B.super.foo() }}
We call the default implementation of method foo() from eitherinterface A or B instead of implementing our own.
![Page 31: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/31.jpg)
Going back to the example of forEach method, how can we force it'sdefault implementation all the iterable collections?
![Page 32: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/32.jpg)
Let's take a look at the Java UML for all the iterable Collections:
In order to add a default behaviour to all the iterable collections, adefault forEach method was added to the Iterable<E> interface.
![Page 33: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/33.jpg)
We can find its default implementation in java.lang.Iterableinterface:
@FunctionalInterfacepublic interface Iterable { Iterator iterator(); default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }}
![Page 34: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/34.jpg)
The forEach method takes a java.util.function.Consumerfunctional interface type as a parameter, which enables us to pass in a
lambda or a method reference as follows:List<?> list = ...list.forEach(System.out::println);
This is also valid for Sets and Queues, for example, since both classesimplement the Iterable interface.
![Page 35: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/35.jpg)
SummarySummaryDefault methods can be seen as a bridge between lambdas and JDKlibraries.Can be used in interfaces to provide default implementations ofotherwise abstract methods.
Clients can optionally implement (override) them.static methods are now also allowed in interfaces.
Can eliminate the need for utility classes like .Collections
![Page 36: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/36.jpg)
AccumulatorsAccumulatorsScalable updatable variables
![Page 37: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/37.jpg)
AccumulatorsAccumulatorsThe continual evolution of uses of concurrency and parallelism in
applications requires continual evolution in library support. For thispurpose, the Accumulators were introduced.
![Page 38: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/38.jpg)
AccumulatorsAccumulatorsMaintaining a single count, sum, etc., that is updated by possibly many
threads is a common scalability problem.A set of new classes were created for that purpose:
DoubleAccumulatorDoubleAdderLongAccumulatorLongAdder
![Page 39: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/39.jpg)
AccumulatorsAccumulatorsPackage java.util.concurrent mechanisms synchronized
operations between threads, however if all you want to do is incrementa variable across threads, it was overkill and then some.
These classes are usually preferable to alternatives when multiplethreads update a common value that is used for purposes such as
summary statistics that are frequently updated but less frequently read.
![Page 40: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/40.jpg)
AccumulatorsAccumulatorsBoth the DoubleAdder and LongAdder classes can be seen as specific
subsets of the DoubleAccumulator and LongAccumulatorfunctionality.
The call new DoubleAdder() is equivalent to:new DoubleAccumulator((x, y) -> x + y, 0.0).
The call new LongAdder() is equivalent to:new LongAccumulator((x, y) -> x + y, 0L).
![Page 41: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/41.jpg)
ExamplesExamples
![Page 42: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/42.jpg)
DoubleAccumulator da = new DoubleAccumulator((x,y) -> x + y, 0.0);List<Double> doubles = Arrays.asList(1.0, 2.0, 3.0, 4.0, 10.0);doubles.forEach(da::accumulate);
System.out.println("Result: " + da.doubleValue());
Output:Result: 20
![Page 43: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/43.jpg)
LongAdder la = new LongAdder();List<Long> longs = Arrays.asList(10L, 20L, 30L, 40L, 100L);longs.forEach(la::add);
System.out.println("Result: " + la.longValue());
Output:Result: 200
![Page 44: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/44.jpg)
java.util.streamjava.util.streamfilter/map/reduce for Java
![Page 45: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/45.jpg)
java.util.streamjava.util.streamList<Student> students = …;Stream stream = students.stream(); // sequential version
// parallel versionStream parallelStream = students.parallelStream();
traversed onceinfinitelazy
![Page 46: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/46.jpg)
java.util.streamjava.util.streamStream sourcesStream sources
CollectionsCollections
Set<Student> set = new LinkedHashSet<>();Stream<Student> stream = set.stream();
GeneratorsGenerators
Random random = new Random();Stream<Integer> randomNumbers = Stream.generate(random::nextInt);
From other streamsFrom other streams
Stream newStream = Stream.concat(stream, randomNumbers);
![Page 47: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/47.jpg)
java.util.streamjava.util.streamIntermediate operationsIntermediate operations
.filter - excludes all elements that don’t match a Predicate
.map - perform transformation of elements using a Function
.flatMap - transform each element into zero or more elements byway of another Stream.peek - performs some action on each element.distinct - excludes all duplicate elements (equals()).sorted - orderered elements (Comparator).limit - maximum number of elements.substream - range (by index) of elementsList<Person> persons = ...;Stream<Person> tenPersonsOver18 = persons.stream() .filter(p -> p.getAge() > 18) .limit(10);
More examples at: .https://github.com/cst2301-pt13/library-solution
![Page 48: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/48.jpg)
java.util.streamjava.util.streamTerminating operationsTerminating operations
1. Obtain a stream from some sources2. Perform one or more intermidate operations3. Perform one terminal operation
reducers like reduce(), count(), findAny(), findFirst()collectors (collect())forEachiterators
List<Person> persons = ..;List<Student> students = persons.stream() .filter(p -> p.getAge() > 18) .map(Student::new) .collect(Collectors.toList());
![Page 49: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/49.jpg)
java.util.streamjava.util.streamParallel & SequentialParallel & Sequential
List<Person> persons = ..;List<Student> students = persons.stream() .parallel() .filter(p -> p.getAge() > 18) .sequential() .map(Student::new) .collect(Collectors.toCollection(ArrayList::new));
![Page 50: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/50.jpg)
java.timejava.timeYet Another Java Date/Time API
![Page 51: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/51.jpg)
java.timejava.timeCurrent TimeCurrent Time
Clock clockUTC = Clock.systemUTC();
Clock clockDefault = Clock.systemDefaultZone();
![Page 52: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/52.jpg)
java.timejava.timeTime ZonesTime Zones
ZoneId zone = ZoneId.systemDefault();
ZoneId zoneBerlin = ZoneId.of("Europe/Berlin");Clock clock = Clock.system(zoneBerlin);
![Page 53: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/53.jpg)
java.timejava.timeHuman Readable TimeHuman Readable Time
class LocalDate { public static LocalDate now() { ... } public static LocalDate now(ZoneId zone) { ... } public static LocalDate now(Clock clock) { ... }}
LocalDate date = LocalDate.now();System.out.printf("%s-%s-%s", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
![Page 54: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/54.jpg)
java.timejava.timeDoing CalculationsDoing Calculations
LocalTime lt = LocalTime.now();lt.plus(5, ChronoUnit.HOURS);
lt.plusHours(5);
Duration dur = Duration.of(5, ChronoUnit.HOURS);lt.plus(dur);
![Page 55: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/55.jpg)
Documentation & InterestingDocumentation & InterestingLinksLinks
http://download.java.net/jdk8/docs/http://download.java.net/jdk8/docs/api/https://blogs.oracle.com/thejavatutorials/entry/jdk_8_documentation_developer_previewhttp://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
![Page 56: Introduction to new features in java 8](https://reader030.vdocuments.site/reader030/viewer/2022020116/55a6a94f1a28abf16a8b4653/html5/thumbnails/56.jpg)
Questions?Questions?