SoCal Code Camp 2015: An introduction to Java 8

Post on 13-Apr-2017

400 views 2 download

Transcript of SoCal Code Camp 2015: An introduction to Java 8

1

Java 8Level Up with new features!

Socal Code Camp 201514 Nov, Los Angeles

2

Java 8Level Up with new features!

Image: http://blog.takipi.com/

3

Who am I?

@cganoo@cganoo

Trademarks and pictures belong to respective copyright owners

@caganoo

4

Agenda

Introduction

Default Methods

Lambdas

Streams

CompletableFuture

Demo

5

Intro

Popularity Rank on GitHub

Popu

larit

y Ra

nk o

n St

ackO

verfl

ow

https://redmonk.com/sogrady/2015/07/01/language-rankings-6-15/

6

Intro

https://dzone.com/articles/java-version-statistics-2015http://www.oracle.com/technetwork/java/eol-135779.html

7

Default Methods

Interview Question:

What is an interface in java?

8

Default Methods

Interfaces can now declare methods with implementation: Static methods Default Methods

9

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

10

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

Collections.sort(numbers);

11

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

Collections.sort(numbers);

Collections.sort(numbers, myComparator);

12

Default Methods

List<Integer> numbers = Arrays.asList(3, 5, 1);

numbers.sort(Comparator.naturalOrder());

13

Default Methods

14

Default Methodspublic 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!}

15

Default Methods

Interview Question:

What's the difference between Abstract classes and Interfaces?

16

Default Methods

17

Default Methods

3 Resolution Rules:

Classes always win Then, sub-interfaces win Then, the inheriting class inheriting has to

explicitly select

18

Lambdas

Image: http://blog.takipi.com/

19

Lambdas

Concise way to express Behavior Parametrization

20

LambdasList<Student> filterByGrade(students, grade) {

List<Student> result = new ArrayList<>();

for (Student student : students) {if

( student.getGrade().equals(grade) ) {result.add(student);

}}return result;

}

21

Lambdas

List<Student> gradeAStudents = filterByGrade(students, "A");

List<Student> gradeBStudents = filterByGrade(students, "B");

22

LambdasList<Student> filterByAge(students, age) {

List<Student> result = new ArrayList<>();

for (Student student : students) {if ( student.getAge() > age ) {

result.add(student);}

}return result;

}

23

Lambdas

List<Student> oldStudents = filterByAge(students, 30);

List<Student> youngStudents = filterByAge(students, 20);

Value Parameterization!

24

Lambdaspublic 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;

}

25

Lambdas

filter( students,

(Student s) -> "A".equals(s.getGrade()));

26

LambdasComparator<Student> c = new Comparator<Student>() {

public int compare(Student a1, Student a2) {

return a1.getAge().compareTo(a2.getAge());

}};

27

LambdasComparator<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());

28

Lambdas

So where can you use lambdas?

In the context of a functional interface

29

Lambdas

A functional interface is an interface that specifies exactly one abstractmethod

30

Lambdas@FunctionalInterfacepublic interface Runnable {

public abstract void run();}

@FunctionalInterfacepublic interface Callable<V> {

V call() throws Exception;}

31

Lambdas

Thread thread1 = new Thread(new Runnable() { @Override public void run(){ doSomething(); }}); thread1.start();

32

Lambdas

Thread thread1 = new Thread(new Runnable() { @Override public void run(){ doSomething(); }}); thread1.start();

new Thread(() -> doSomething()).start();

33

Lambdas@FunctionalInterfacepublic interface Predicate<T> {

boolean test(T t);}

@FunctionalInterfacepublic interface Function<T, R> {

R apply(T t);}

34

Lambdas

Method References:

items.forEach((x) -> System.out.print(x));

items.forEach(System.out::print);

35

Lambdas

Image taken from the book ‘Java 8 in Action’ by Urma, Fusco and Mycroft

36

Streams

Image: http://www.123rf.com/photo_5391089_blue-tsunami-wave-two.html

37

Streams

Stream is a sequence of elements from a source that supports data processing operations

38

StreamsMotivation: Collections is the most heavily used API in

Java

39

StreamsMotivation: Collections is the most heavily used API in

Java Lacks declarative syntax

40

StreamsMotivation: Collections is the most heavily used API in

Java Lacks declarative syntax Lacks easy parallelization API

41

Streams

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

42

Streams

Streams are Collections on steroids!

43

Streams

List<String> someStudentNames =students.stream()

.filter(s -> s.getAge() > 20)

.sorted(comparing(Student::getGrade)).map(Student::getName).collect(toList());

44

Streams

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

45

Streams

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

46

StreamsIntermediate Operations: Return Stream<X>

filter Predicate<T> T -> booleanmap Function<T, R> T -> Rsorted Comparator<T> (T, T) -> intdistinct

47

StreamsTerminal Operations:

forEach Consumer<T> T -> voidcount Returns a longcollect Collector<T, A, R> reduce T identity, BinaryOperator<T>

48

Streams

Generating Streams:

Stream.of("Code", "Camp")

Arrays.stream(new int[] {1, 2})

Files.lines() (Java NIO)

49

Streams

Generating Infinite Streams:

Stream.iterate(0, n -> n + 2)

Stream.generate(Math::random)

50

CF

Interview Question:

What's the difference between Concurrency and Parallelism?

51

CF

http://joearms.github.io/2013/04/05/concurrent-and-parallel-programming.html

52

CF

Interview Question:

What's a Future in Java?

53

CF

Future models an asynchronous computation and provides a reference to its result that will be available when the computation itself is completed

54

CF

Future<Double> future = executor.submit(

() -> doSomething());doSomethingElse();

try {Double result =

future.get(1, TimeUnit.SECONDS);} catch (TimeoutException e) {...}

55

CFpublic 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;}

56

CF

public Future<Double> getPrice (String product) { return CF.supplyAsync(() -> price(product))

.exceptionally(() -> 0.0);}

57

Question

Parallel Streams vs CompletableFutures

58

CF

Which one to prefer?

59

CFPattern 1: Async Sequencing

thenAccept*Run a function when complete

thenApply*Convert the result using a function when complete

60

CFPattern 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

61

CF

CF<String> user = CF.supplyAsync(() ->

"John");CF<String> id =

CF.supplyAsync( () -> "1");

user.thenCombineAsync(id, (u, i) -> u +

i).thenAccept(System.out::println);

62

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

63

Demo

64

Demo

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

65

Demo

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

66

Demo

C03E https://github.com/cganoo/codecamptweetfetcher https://github.com/cganoo/codecamptweetsearcher

The next few slides show screenshots from the demo

67

Text Search in ES

68

Summary metrics in ES

69

Custom Dashboard in ES

70

AWS Cloudwatch Metrics

71

AWS Lambda Cloudwatch Logs

72

Questions?