SlideShare ist ein Scribd-Unternehmen logo
1 von 72
Java 8
Level Up with new features!
1
Socal Code Camp 2015
14 Nov, Los Angeles
Java 8
Level Up with new features!
2
Image: http://blog.takipi.com/
Who am I?
3
@cganoo
@cganoo
Trademarks and pictures belong to respective copyright owners
@caganoo
Agenda
 Introduction
 Default Methods
 Lambdas
4
 Streams
 CompletableFuture
 Demo
Intro
5
Popularity Rank on GitHub
PopularityRankonStackOverflow
https://redmonk.com/sogrady/2015/07/01/language-rankings-6-15/
Intro
6
https://dzone.com/articles/java-version-statistics-2015http://www.oracle.com/technetwork/java/eol-135779.html
Default Methods
7
Interview Question:
What is an interface in java?
Default Methods
Interfaces can now declare methods with
implementation:
 Static methods
 Default Methods
8
Default Methods
List<Integer> numbers = Arrays.asList(3, 5, 1);
9
Default Methods
List<Integer> numbers = Arrays.asList(3, 5, 1);
Collections.sort(numbers);
10
Default Methods
List<Integer> numbers = Arrays.asList(3, 5, 1);
Collections.sort(numbers);
Collections.sort(numbers, myComparator);
11
Default Methods
List<Integer> numbers = Arrays.asList(3, 5, 1);
numbers.sort(Comparator.naturalOrder());
12
Default Methods
13
Default Methods
14
public class Dog implements Bark {
// No overridden method
}
public interface Bark {
default String bark() {
return "Woof Woof!";
}
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // Woof Woof!
}
Default Methods
15
Interview Question:
What's the difference between Abstract
classes and Interfaces?
Default Methods
16
Default Methods
17
3 Resolution Rules:
 Classes always win
 Then, sub-interfaces win
 Then, the inheriting class inheriting has to
explicitly select
Lambdas
18
Image: http://blog.takipi.com/
Lambdas
19
Concise way to express
Behavior Parametrization
Lambdas
20
List<Student> filterByGrade(students, grade) {
List<Student> result = new ArrayList<>();
for (Student student : students) {
if ( student.getGrade().equals(grade) ) {
result.add(student);
}
}
return result;
}
Lambdas
21
List<Student> gradeAStudents =
filterByGrade(students, "A");
List<Student> gradeBStudents =
filterByGrade(students, "B");
Lambdas
22
List<Student> filterByAge(students, age) {
List<Student> result = new ArrayList<>();
for (Student student : students) {
if ( student.getAge() > age ) {
result.add(student);
}
}
return result;
}
Lambdas
23
List<Student> oldStudents =
filterByAge(students, 30);
List<Student> youngStudents =
filterByAge(students, 20);
Lambdas
24
public interface Predicate<T> {
boolean test(T t);
}
List<T> filter(List<T> list, Predicate<T> p) {
List<T> result = new ArrayList<>();
for(T e: list) {
if(p.test(e)){ result.add(e); }
}
return result;
}
Lambdas
25
filter(
students,
(Student s) -> "A".equals(s.getGrade())
);
Lambdas
26
Comparator<Student> c = new Comparator<Student>()
{
public int compare(Student a1, Student a2) {
return a1.getAge().compareTo(a2.getAge());
}
};
Lambdas
27
Comparator<Student> c = new Comparator<Student>()
{
public int compare(Student a1, Student a2) {
return a1.getAge().compareTo(a2.getAge());
}
};
Comparator<Student> c =
(Student a1, Student a2) ->
a1.getGrade().compareTo(a2.getGrade());
Lambdas
28
So where can you use lambdas?
In the context of a functional interface
Lambdas
29
A functional interface is an interface that
specifies exactly one abstract
method
Lambdas
30
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
Lambdas
31
Thread thread1 = new Thread(new Runnable() {
@Override
public void run(){
doSomething();
}
});
thread1.start();
Lambdas
32
Thread thread1 = new Thread(new Runnable() {
@Override
public void run(){
doSomething();
}
});
thread1.start();
new Thread(() -> doSomething()).start();
Lambdas
33
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Lambdas
34
Method References:
items.forEach((x) -> System.out.print(x));
items.forEach(System.out::print);
Lambdas
35
Image taken from the book ‘Java 8 in Action’ by Urma, Fusco and Mycroft
Streams
36
Image: http://www.123rf.com/photo_5391089_blue-tsunami-wave-two.html
Streams
37
Stream is a sequence of elements from a
source that supports data processing
operations
Streams
Motivation:
38
 Collections is the most heavily used API in
Java
Streams
Motivation:
39
 Collections is the most heavily used API in
Java
 Lacks declarative syntax
Streams
Motivation:
40
 Collections is the most heavily used API in
Java
 Lacks declarative syntax
 Lacks easy parallelization API
Streams
41
Stream is a sequence of elements from a
source that supports data processing
operations:
Fancy iterators that let you manipulate
collections of data in a declarative,
composable and transparently parallel way
Streams
42
Streams are Collections on steroids!
Streams
43
List<String> someStudentNames =
students.stream()
.filter(s -> s.getAge() > 20)
.sorted(comparing(Student::getGrade))
.map(Student::getName)
.collect(toList());
Streams
44
List<Student> someStudents =
students.stream()
.filter(s -> s.getAge() > 20)
.sorted(comparing(Student::getGrade))
.map(Student::getName)
.collect(toList());
Get a list of the names of all students, sorted by their
grades and who are above 20 years of age
Streams
45
List<Student> someStudents =
students.parallelStream()
.filter(s -> s.getAge() > 20)
.sorted(comparing(Student::getGrade))
.map(Student::getName)
.collect(toList());
Get a list of the names of all students, sorted by their
grades and who are above 20 years of age
Streams
46
Intermediate Operations: Return Stream<X>
filter Predicate<T> T -> boolean
map Function<T, R> T -> R
sorted Comparator<T> (T, T) -> int
distinct
Streams
47
Terminal Operations:
forEach Consumer<T> T -> void
count Returns a long
collect Collector<T, A, R>
reduce T identity, BinaryOperator<T>
Streams
48
Generating Streams:
 Stream.of("Code", "Camp")
 Arrays.stream(new int[] {1, 2})
 Files.lines() (Java NIO)
Streams
49
Generating Infinite Streams:
 Stream.iterate(0, n -> n + 2)
 Stream.generate(Math::random)
CF
50
Interview Question:
What's the difference between
Concurrency and Parallelism?
CF
51
http://joearms.github.io/2013/04/05/concurrent-and-parallel-programming.html
CF
52
Interview Question:
What's a Future in Java?
CF
53
Future models an asynchronous computation and
provides a reference to its result that will be available
when the computation itself is completed
CF
54
Future<Double> future = executor.submit(
() -> doSomething());
doSomethingElse();
try {
Double result =
future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {...}
CF
55
public Future<Double> getPrice(String product) {
CF<Double> f = new CF<>();
new Thread(() -> {
try {
double price = price(product);
f.complete(price);
} catch (Exception ex) {
f.completeExceptionally(ex);
}
}).start();
return f;
}
CF
56
public Future<Double> getPrice (String product) {
return CF.supplyAsync(() -> price(product))
.exceptionally(() -> 0.0);
}
Question
57
Parallel Streams vs CompletableFutures
CF
58
Which one to prefer?
CF
59
Pattern 1: Async Sequencing
thenAccept*
Run a function when complete
thenApply*
Convert the result using a function when complete
CF
60
Pattern 2: Async Join
thenAcceptBoth*
Run a function when both futures are done
thenCombine*
Convert the result of 2 futures into a new thing
when both are done
CF
61
CF<String> user =
CF.supplyAsync(() -> "John");
CF<String> id =
CF.supplyAsync( () -> "1");
user
.thenCombineAsync(id, (u, i) -> u + i)
.thenAccept(System.out::println);
References
 Java 8 in Action: https://www.manning.com/books/java-8-in-action
 @Winterberg: http://winterbe.com/posts/2014/03/16/java-8-tutorial/
 IntelliJ for Java Projects
62
Demo
63
Demo
64
Demo 1:
• Run code to periodically fetch tweets from Twitter
• Store the fetched tweets somewhere
Tech Stack used:
• AWS Lambda to create scheduled function
• AWS S3 to store fetched tweets
• Twitter Streaming Endpoint to fetch tweets
Demo
65
Demo 2:
• Index the stored tweets into an ElasticSearch cluster
• Explore and visualize patterns using Kibana Dashboards
Tech Stack used:
• AWS Lambda to create a function reacting to S3 events
• AWS ElasticSearch Service
• Kibana 4
Demo
66
C03E
 https://github.com/cganoo/codecamptweetfetcher
 https://github.com/cganoo/codecamptweetsearcher
The next few slides show screenshots from the demo
Text Search in ES
67
Summary metrics in ES
68
Custom Dashboard in ES
69
AWS Cloudwatch Metrics
70
AWS Lambda Cloudwatch Logs
71
72
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++Next
Sergey Platonov
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
Wiwat Ruengmee
 

Was ist angesagt? (20)

Klee introduction
Klee  introductionKlee  introduction
Klee introduction
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Symbolic Execution And KLEE
Symbolic Execution And KLEESymbolic Execution And KLEE
Symbolic Execution And KLEE
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++Next
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
 
Simulado java se 7 programmer
Simulado java se 7 programmerSimulado java se 7 programmer
Simulado java se 7 programmer
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
Java language fundamentals
Java language fundamentalsJava language fundamentals
Java language fundamentals
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196
 
Java8 - Interfaces, evolved
Java8 - Interfaces, evolvedJava8 - Interfaces, evolved
Java8 - Interfaces, evolved
 

Ähnlich wie SoCal Code Camp 2015: An introduction to Java 8

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 

Ähnlich wie SoCal Code Camp 2015: An introduction to Java 8 (20)

Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
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...
 
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
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
Java Micro-Benchmarking
Java Micro-BenchmarkingJava Micro-Benchmarking
Java Micro-Benchmarking
 
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 Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 

KĂźrzlich hochgeladen

Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
SUHANI PANDEY
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

KĂźrzlich hochgeladen (20)

2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 

SoCal Code Camp 2015: An introduction to Java 8

Hinweis der Redaktion

  1. Nov 14 2015 Socal CodeCamp 2015 Talk
  2. http://www.oracle.com/us/technologies/java/duke-424174.html Creator: Joe Palrang Duke was designed to represent a "software agent" that performed tasks for the user. Duke was the interactive host that enabled a new type of user interface that went beyond the buttons, mice, and pop-up menus of the desktop computing world
  3. RedMonk Q3 2014 Programming Language Rankings X axis: Popularity Rank on GitHub (by # of projects) Y axis: Popularity Rank on StackOverflow (by # of tags) GitHub and Stack Overflow are used here first because of their size and second because of their public exposure of the data necessary for the analysis
  4. RedMonk Q3 2014 Programming Language Rankings X axis: Popularity Rank on GitHub (by # of projects) Y axis: Popularity Rank on StackOverflow (by # of tags) GitHub and Stack Overflow are used here first because of their size and second because of their public exposure of the data necessary for the analysis
  5. Language construct that groups related methods together into a contract. (HAS-A vs IS-A signaled by an abstract class) Java 8 API introduces many new methods on existing interfaces, such as the sort method on the List
  6. Java 8 API introduces many new methods on existing interfaces, such as the sort method on the List How would maintainers of other libraries like Guava feel if they suddenly had to implement sort? The main users of default methods are library designers. default methods were introduced to evolve libraries such as the Java API in a compatible way But even if you are an application developer this is important: default methods can help structure your programs by providing a flexible mechanism for multiple inheritance of behavior: a class can inherit default methods from several interface/classes There are three kinds of compatibility when introducing a change to a Java program: binary, source, and behavioral compatibilities Adding a method to an interface is binary compatible and behavioral compatible but NOT source compatible
  7. Overlap: They both can contain abstract methods and methods with a body. Difference 1: A class can extend only from one abstract class, but a class can implement multiple interfaces. Difference 2: An abstract class can enforce a common state constants, members, method stubs and defined methods, whereas interfaces can only have constants methods stubs AND (now) default methods Difference 3: Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default). Meta Difference: Abstract class is for polling together behavior whereas interfaces act like contracts
  8. What if the class implements two interfaces and both those interfaces define a default method with the same signature
  9. 1 Classes always win: A method declaration in the class or a superclass takes priority over any default method declaration. 2 Otherwise, sub-interfaces win: the method with the same signature in the most specific default-providing interface is selected. (If B extends A , B is more specific than A ). 3 Finally, if the choice is still ambiguous, the class inheriting from multiple interfaces has to explicitly select which default method implementation to use by overriding it and calling the desired method explicitly: new syntax X.super.m(…) Where X is the superinterface whose method m you want to call.
  10. 1. Behavior parameterization is a software development pattern that lets you handle frequent requirement changes. 2. It is the ability for a method to take multiple different behaviors as parameters and use them internally to accomplish different behaviors 3. In this sense its similar to Strategy Design pattern 4. Prior to Java 8, it could be encoded using anonymous classes The Java 8 feature of passing code to methods (and also being able to return it and incorporate it into data structures) also provides access to a whole range of additional techniques that are commonly referred to as functional-style programming Java 8 decided to allow methods to be values—to make it easier for you to program. Moreover, the Java 8 feature of methods as values forms the basis of various other Java 8 features (such as Stream s)
  11. You could combine the grade and age into one method called 'filter': But we'll still need a way to differentiate what attrobute to filter on We could use flags but thats really ugly What if the requirements mandate filtering based on not just a single attribute but a combination of attributes? So far we have parameterized the filter method with values such as a String, an Integer, or a boolean. But in this case what w eneed is a better way to tell your filter method the selection criteria for students. Creating a StudentPredicate interface and having multiple predicate objects implement that and then passing that interface as a second arg to filterStudents method can solve this in theory. Cons: Unnecessary declaration of multiple objects/interfaces. Anonymous classes could be used but they are bulky and distracting We could use built-in method: students.stream().filter(p -> p.age = 20).forEach(p -> System.out.println(p));
  12. 1. An interface is still a functional interface if it has many default methods as long as it specifies only one abstract method. 2. The signature of the abstract method of the functional interface essentially describes the signature of the lambda expression. We call this abstract method a function descriptor
  13. Note that none of the new functional interfaces allow for a checked exception to be thrown. You have two options if you need a lambda expression to throw an exception: define your own functional interface that declares the checked exception, or wrap the lambda with a try/catch block
  14. Note that none of the new functional interfaces allow for a checked exception to be thrown. You have two options if you need a lambda expression to throw an exception: define your own functional interface that declares the checked exception, or wrap the lambda with a try/catch block
  15. The type of a lambda is deduced from the context in which the lambda is used. The type expected for the lambda expression inside the context (for example, a method parameter that it’s passed to or a local variable that it’s assigned to) is called the target type
  16. https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html Lambdas and Closures: A closure is an instance of a function that can reference nonlocal variables of that function with no restrictions Now Java 8 lambdas and anonymous classes do something similar to closures: they can be passed as argument to methods and can access variables outside their scope. But they have a restriction: they can’t modify the content of local variables of a method in which the lambda is defined Those variables have to be implicitly final. It helps to think that lambdas close over values rather than variables
  17. Allows us to reference constructors or methods without executing them. Method references and Lambda are similar in that they both require a target type that consist of a compatible functional interface. Java 8 enables you to pass references of methods or constructors via the :: keyword 4 types: Static MR: Arrays.sort(items, (a, b) -> Util.compareItems(a, b)); Arrays.sort(items, Util::compareItems); Instance MR: items.forEach((x) -> System.out.print(x)); items.forEach(System.out::print); Reference to a method of arbitrary instance items.forEach((x) -> { x.publish(); }); items.forEach(Item::publish); Constructor reference ConstructorReference cref = Item::new; Item item = cref.constructor();
  18. Streams are an update to the Java API that lets you manipulate collections of data in a declarative way (you express a query rather than code an ad hoc implementation for it) 1. Sequence of elements—Like a collection, a stream provides an interface to a sequenced set of values of a specific element type. But Collections are about data; streams are about computations. 2. Source—Streams consume from a data-providing source such as collections, arrays, or I/O resources. 3. Data processing operations—Streams support database-like operations and common operations from functional programming languages to manipulate data, such as filter, map, reduce, find, match, sort,
  19. Much business logic entails database-like operations such as grouping, filtering, limiting a list of entities by some constraint (for example, all old students) We keep reimplementing these operations using iterators. In contrast most databases let you specify such operations declaratively: Express what you want done rather than how you want it done!
  20. To gain performance you’d need to process it in parallel and leverage multicore architectures. But writing parallel code is complicated in comparison to working with iterators. In addition, it’s no fun to debug.
  21. Declarative: Write code in a declarative way Composable: Allows chaining to create data processing pipelines Paralellizable: parallelXXX
  22. In coarsest terms, the difference between collections and streams has to do with when things are computed: 1. A collection is an in-memory data structure that holds all the values the data structure currently has 2. A Stream is a conceptually fixed data structure (you can’t add or remove elements from it) whose elements are computed on demand 3. You can see a stream as a set of values spread out in time. In contrast, a collection is a set of values spread out in space (here, computer memory), which all exist at a single point in time Collections are about data; streams are about computations. Netflix DVD vs Netflix Stream example
  23. Sorted takes a Comparator: Stream<T> sorted(Comparator<? super T> comparator) static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor)
  24. Stream operations have two important characteristics: 1. Pipelining: Many stream operations return a stream themselves, allowing operations to be chained and form a larger pipeline allowing for laziness and short-circuiting. 2. Internal iteration: stream operations do the iteration behind the scenes for you. Stream operations that can be connected are called intermediate operations, and operations that close a stream are called terminal operations Intermediate: filter, map, limit, skip, distinct, sorted Terminal: forEach, collect, count, anyMatch, noneMatch, allMatch, findFirst, findAny, reduce/fold
  25. What exactly happens when you call the method parallelStream() ? How many threads are being used? What are the performance benefits? Because operations such as filter (or sorted , map , and collect ) are available as high-level building blocks that don’t depend on a specific threading model, their internal implementation could be single-threaded or potentially maximize your multicore architecture transparently
  26. forEach: Consumes each element from a stream and applies a lambda to each of them. The operation returns void. Count: Returns the number of elements in a stream. The operation returns a long. Collect: Reduces the stream to create a collection such as a List, a Map, or even an Integer <R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) Reduce: T reduce(T identity, BinaryOperator<T> accumulator) // Reduce int sum = numbers.stream().reduce(0, (a, b) -> a + b); reduce takes two arguments: ■ An initial value, here 0. ■ A BinaryOperator<T> to combine two elements and produce a new value; here you use the lambda (a, b) -> a + b. There’s also an overloaded variant of reduce that doesn’t take an initial value, but it returns an Optional object Optional<Integer> max = numbers.stream().reduce(Integer::max);
  27. You can also get an empty stream using the empty method as follows: Stream<String> emptyStream = Stream.empty();
  28. Iterate: Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) Generate: Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements etc static <T> Stream<T> generate(Supplier<T> s) https://jaxenter.com/java-performance-tutorial-how-fast-are-the-java-8-streams-118830.html
  29. Concurrency is related to how an application handles multiple tasks it works on. An application may process one task at at time (sequentially) or work on multiple tasks at the same time (concurrently). Parallelism on the other hand, is related to how an application handles each individual task. An application may process the task serially from start to end, or split the task up into subtasks which can be completed in parallel. [1] Concurrency: Main goal is to perform several loosely related tasks on the same CPUs, keeping the core as busy as possible to maximize the throughput of your application, what you really want to achieve is to avoid blocking a thread and wasting its computational resources while waiting [2] Paralellism: Split an operation into multiple suboperations and perform those suboperations in parallel on different cores, CPUs, or even machines. Specifically for Multicore processors we can take advantage via: FJ Framework + parallel streams In recent years, two trends are obliging us to rethink the way we write software. The first trend is related to the hardware on which we run our applications, and the second trend concerns how applications are structured and particularly how they interact with each other
  30. Since Java 1.5
  31. Futures still dont allow you to write concise concurrent code. CompletableFuture does. For example, it’s difficult to express dependencies between results of a Future ; declaratively it’s easy to say, “When the result of the long computation is available, please send its result to another long computation, and when that’s done, combine its result with the result from another query.” But implementing this with the operations available in a Future is a different story Combining two asynchronous computations in one—both when they're independent and when the second depends on the result of the first ■ Waiting for the completion of all tasks performed by a set of Future s ■ Waiting for the completion of only the quickest task in a set of Future s (possibly because they’re trying to calculate the same value in different ways) and retrieving its result ■ Programmatically completing a Future (that is, by manually providing the result of the asynchronous operation) ■ Reacting to a Future completion (that is, being notified when the completion happens and then having the ability to perform a further action using the result of the Future , instead of being blocked waiting for its result
  32. The supplyAsync method accepts a Supplier as argument and returns a Completable- Future that will be asynchronously completed with the value obtained by invoking that Supplier . This Supplier will be run by one of the Executor s in the ForkJoin- Pool , but you can specify a different Executor by passing it as a second arg Tenants for Reactive Programming Avoid Blocking Thread (to optimize usage of all available cores) Avoid changing threads (to optimize our use of cpu caches) Avoid crippling failure (failure in a subsystem should be encapsulated and handled) [1] and [2] are competing concerns
  33. Parallel Streams and CompletableFutures both internally use the same common pool that by default has a fixed number of threads equal to the one returned by: Runtime.getRuntime().availableProcessors() . Nevertheless, CompletableFutures have an advantage because, in contrast to what’s offered by the parallel Streams API , they allow you to specify a different Executor to submit their tasks to. This allows you to configure this Executor , and in particular to size its thread pool, in a way that better fits the requirements of your application.
  34. ■ If you’re doing computation-heavy operations with no I/O, then the Stream interface gives the simplest implementation and one likely to be the most efficient (if all threads are compute-bound, then there’s no point in having more threads than processor cores). ■ On the other hand, if your parallel units of work involve waiting for I/O (including network connections), then CompletableFutures give more flexibility and the ability to match the number of threads to the wait/computer, or W/C, ratio as discussed previously. Another reason to avoid using parallel streams when I/O waits are involved in the stream-processing pipeline is that the laziness of streams can make it harder to reason about when the waits actually happen.
  35. * = additional behavior happens on current thread (blocking) *Async = additional behavior happens elsewhere
  36. * = additional behavior happens on current thread (blocking) *Async = additional behavior happens elsewhere