Slide 1

Slide 1 text

Java 8 on Android Alex Florescu YPlan @flor3scu

Slide 2

Slide 2 text

Outline • Backward compatible features • Lambdas, method references etc. • Android N+ only features • Streams, default methods etc. • Setup: how to get this working • Other useful tidbits and analysis

Slide 3

Slide 3 text

Notes • Slides are online • All code is online

Slide 4

Slide 4 text

Backward-compatible features • Lambdas • Method references • Type annotations

Slide 5

Slide 5 text

API support • Official website
 “Also available on API level 23 and lower” • Google I/O 2016
 “Backward compatible with Gingerbread”

Slide 6

Slide 6 text

Backward-compatible features • Lambdas • Method references • Type annotations

Slide 7

Slide 7 text

Lambdas & Method references

Slide 8

Slide 8 text

Functional interface • Has exactly one abstract method • Can annotate with @FunctionalInterface • Not necessary for using lambdas with it

Slide 9

Slide 9 text

OnClickListener public interface OnClickListener {
 void onClick(View v);
 }

Slide 10

Slide 10 text

Functional interface • A lot of standard ones added in java.util.function • Consumer — an operation that accepts a single input argument and returns no result • Function — a function that accepts one argument and produces a result • Predicate — a predicate (boolean-valued function) of one argument • Supplier — a supplier of results

Slide 11

Slide 11 text

Lambdas & Method references

Slide 12

Slide 12 text

Lambdas Language construct that simplifies (or flattens) anonymous inner classes

Slide 13

Slide 13 text

Setting listener button1.setOnClickListener(new View.OnClickListener() {
 @Override public void onClick(View v) {
 Snackbar.make(mainPanel, "Click listener
 triggered", Snackbar.LENGTH_SHORT).show();
 }
 });

Slide 14

Slide 14 text

Setting listener button1.setOnClickListener(new View.OnClickListener() {
 @Override public void onClick(View v) {
 Snackbar.make(mainPanel, "Click listener
 triggered", Snackbar.LENGTH_SHORT).show();
 }
 });

Slide 15

Slide 15 text

Setting listener button1.setOnClickListener(v -> 
 Snackbar.make(mainPanel, "Click listener triggered", 
 Snackbar.LENGTH_SHORT).show());

Slide 16

Slide 16 text

Setting listener button1.setOnClickListener(v -> 
 Snackbar.make(mainPanel, "Click listener triggered", 
 Snackbar.LENGTH_SHORT).show());

Slide 17

Slide 17 text

Lambda examples // Lambda with no parameters
 Runnable r2 = () -> Timber.d("Lambda test");

Slide 18

Slide 18 text

Example with params participantRedList.setAdapter(
 new ParticipantAdapter(
 
 filterParticipants(participants,
 new FilterCondition() {
 @Override
 public boolean accept(Participant candidate) {
 return candidate.getTeamColour() == TeamColour.RED;
 }
 })));

Slide 19

Slide 19 text

Example with params participantRedList.setAdapter(
 new ParticipantAdapter(
 
 filterParticipants(participants,
 new FilterCondition() {
 @Override
 public boolean accept(Participant candidate) {
 return candidate.getTeamColour() == TeamColour.RED;
 }
 })));

Slide 20

Slide 20 text

Example with params participantRedList.setAdapter(
 new ParticipantAdapter(
 
 filterParticipants(participants,
 new FilterCondition() {
 @Override
 public boolean accept(Participant candidate) {
 return candidate.getTeamColour() == TeamColour.RED;
 }
 })));

Slide 21

Slide 21 text

Example with params participantRedList.setAdapter(
 new ParticipantAdapter(
 filterParticipants(participants,
 (candidate) -> candidate.getTeamColour() == TeamColour.RED)));

Slide 22

Slide 22 text

Example with params participantRedList.setAdapter(
 new ParticipantAdapter(
 filterParticipants(participants,
 (candidate) -> candidate.getTeamColour() == TeamColour.RED)));

Slide 23

Slide 23 text

Syntax p -> p.getAge() >= 18 (a,b) -> a.getAge() < b.getAge() () -> Timber.d(“Ping”) (p) -> {
 Timber.d(“Participant age : %d”, p.getAge());
 return p.getAge() < 18;
 }

Slide 24

Slide 24 text

Syntax p -> p.getAge() >= 18 (a,b) -> a.getAge() < b.getAge() () -> Timber.d(“Ping”) (p) -> {
 Timber.d(“Participant age : %d”, p.getAge());
 return p.getAge() < 18;
 }

Slide 25

Slide 25 text

Syntax p -> p.getAge() >= 18 (a,b) -> a.getAge() < b.getAge() () -> Timber.d(“Ping”) (p) -> {
 Timber.d(“Participant age : %d”, p.getAge());
 return p.getAge() < 18;
 }

Slide 26

Slide 26 text

Syntax p -> p.getAge() >= 18 (a,b) -> a.getAge() < b.getAge() () -> Timber.d(“Ping”) (p) -> {
 Timber.d(“Participant age : %d”, p.getAge());
 return p.getAge() < 18;
 }

Slide 27

Slide 27 text

Lambdas & Method references

Slide 28

Slide 28 text

Method references Compact lambda expressions for methods that already have a name

Slide 29

Slide 29 text

Example 
 Collections.sort(participants, new Comparator() {
 @Override
 public int compare(Participant p1, Participant p2) {
 return Integer.compare(p1.getAge(), 
 p2.getAge());
 }
 });

Slide 30

Slide 30 text

Example 
 Collections.sort(participants, (p1, p2) -> Integer.compare(p1.getAge(), 
 p2.getAge()));

Slide 31

Slide 31 text

Example public final class Participant {
 ….
 public static int compareByAge(Participant a, 
 Participant b) {
 return Integer.compare(a.getAge(), b.getAge());
 }
 ….
 }

Slide 32

Slide 32 text

Example public final class Participant {
 ….
 public static int compareByAge(Participant a, 
 Participant b) {
 return Integer.compare(a.getAge(), b.getAge());
 }
 ….
 }

Slide 33

Slide 33 text

Example 
 Collections.sort(participants, new Comparator() {
 @Override
 public int compare(Participant p1, Participant p2) {
 return Participant.compareByAge(p1,p2);
 }
 });

Slide 34

Slide 34 text

Example 
 Collections.sort(participants, (p1, p2) -> Participant.compareByAge(p1, p2));

Slide 35

Slide 35 text

Example 
 Collections.sort(participants,
 Participant::compareByAge);

Slide 36

Slide 36 text

From 
 Collections.sort(participants, new Comparator() {
 @Override
 public int compare(Participant p1, Participant p2) {
 return Participant.compareByAge(p1,p2);
 }
 });

Slide 37

Slide 37 text

To 
 Collections.sort(participants,
 Participant::compareByAge);

Slide 38

Slide 38 text

Android N 
 Collections.sort(participants,
 Comparator.comparingInt(Participant::getAge));

Slide 39

Slide 39 text

Syntax

Slide 40

Slide 40 text

Syntax • Reference to a static method (s) -> String.valueOf(s)

Slide 41

Slide 41 text

Syntax • Reference to a static method (s) -> String.valueOf(s) String::valueOf

Slide 42

Slide 42 text

Syntax • Reference to an instance method of a particular object (o) -> o.toString()

Slide 43

Slide 43 text

Syntax • Reference to an instance method of a particular object (o) -> o.toString() o::toString

Slide 44

Slide 44 text

Syntax • Reference to an instance method of an arbitrary object of a particular type Arrays.sort((a,b) -> a.compareToIgnoreCase(b))

Slide 45

Slide 45 text

Syntax • Reference to an instance method of an arbitrary object of a particular type Arrays.sort((a,b) -> a.compareToIgnoreCase(b)) Arrays.sort(String::compareToIgnoreCase)

Slide 46

Slide 46 text

Syntax • Reference to an instance method of an arbitrary object of a particular type Arrays.sort((a,b) -> a.compareToIgnoreCase(b)) Arrays.sort(String::compareToIgnoreCase)

Slide 47

Slide 47 text

Syntax • Reference to a constructor () -> new String()

Slide 48

Slide 48 text

Syntax • Reference to a constructor () -> new String() String::new

Slide 49

Slide 49 text

Method count

Slide 50

Slide 50 text

Method count • Exploring Java’s Hidden Costs (Jake Wharton) • 23:30 — Lambdas

Slide 51

Slide 51 text

Method count From: https://speakerdeck.com/jakewharton/exploring-hidden-java-costs-360-andev-july-2016?slide=126

Slide 52

Slide 52 text

Comparison with Kotlin • Claims no increase in method count, bytecode inserted directly (see post)

Slide 53

Slide 53 text

Backward-compatible features • Lambdas • Method references • Type annotations

Slide 54

Slide 54 text

Type annotations Annotations can now be used anywhere you use a type

Slide 55

Slide 55 text

Annotations before Java 8 • Method: @Override void onCreate()… • Class: 
 @RunWith(JUnit4Runner.class) 
 public class TestDoggieTreats {… • Parameters, return values
 @NonNull String prepareText(@Nullable input);

Slide 56

Slide 56 text

Type annotations • Anywhere you use a type • Class instantiation: new @Interned MyObject(); • Type cast: myString = (@NonNull String) str; • Implements clause: class UnmodifiableList implements @Readonly List<@Readonly T> { ... } • Throws: void monitorTemperature() throws @Critical TemperatureException { ... }

Slide 57

Slide 57 text

Type annotations • Anywhere you use a type • Class instantiation: new @Interned MyObject(); • Type cast: myString = (@NonNull String) str; • Implements clause: class UnmodifiableList implements @Readonly List<@Readonly T> { ... } • Throws: void monitorTemperature() throws @Critical TemperatureException { ... }

Slide 58

Slide 58 text

Requirements • Using the Jack compiler • Setting language compatibility to 1.8 • (more on that later)

Slide 59

Slide 59 text

Nougat only

Slide 60

Slide 60 text

Nougat only features • Streams • Default and static interface methods • Repeatable annotations

Slide 61

Slide 61 text

Streams A new abstraction that lets you process data in a declarative way

Slide 62

Slide 62 text

Streams Data manipulation like you always dreamed of. Can filter, map & reduce while being traversed, sequentially or in parallel.

Slide 63

Slide 63 text

Example public interface FilterCondition {
 boolean accept(T candidate);
 }
 List filter(List 
 participants, 
 FilterCondition 
 filterCondition)

Slide 64

Slide 64 text

Example List output = new ArrayList<>();
 
 for (Participant participant : participants) {
 if (filterCondition.accept(participant)) {
 output.add(participant);
 }
 }
 
 return output;


Slide 65

Slide 65 text

Example return participants.stream()
 .filter(filterCondition::accept)
 .collect(Collectors.toList());

Slide 66

Slide 66 text

Example return participants.stream()
 .filter(filterCondition::accept)
 .collect(Collectors.toList());

Slide 67

Slide 67 text

Example return participants.stream()
 .filter((participant) -> 
 filterCondition.accept(participant))
 .collect(Collectors.toList());

Slide 68

Slide 68 text

Example return participants.stream()
 .filter(filterCondition::accept)
 .collect(Collectors.toList());

Slide 69

Slide 69 text

Example return participants.stream()
 .filter(filterCondition::accept)
 .collect(Collectors.toList());

Slide 70

Slide 70 text

Example List filter(
 List participants, Predicate predicate)
 
 return participants.stream()
 .filter(predicate)
 .collect(Collectors.toList());

Slide 71

Slide 71 text

Example List filter(
 List participants, Predicate predicate)
 
 return participants.stream()
 .filter(predicate)
 .collect(Collectors.toList());

Slide 72

Slide 72 text

Find the youngest participants
 .stream()
 .min(Comparator.comparingInt(
 Participant::getAge))
 .ifPresent(
 participant -> 
 Timber.d("Youngest participant %s", 
 participant.getName()));


Slide 73

Slide 73 text

Find the youngest participants
 .stream()
 .min(Comparator.comparingInt(
 Participant::getAge))
 .ifPresent(
 participant -> 
 Timber.d("Youngest participant %s", 
 participant.getName()));


Slide 74

Slide 74 text

Find the youngest participants
 .stream()
 .min(Comparator.comparingInt(
 Participant::getAge))
 .ifPresent(
 participant -> 
 Timber.d("Youngest participant %s", 
 participant.getName()));


Slide 75

Slide 75 text

Find the youngest participants
 .stream()
 .min(Comparator.comparingInt(
 Participant::getAge))
 .ifPresent(
 participant -> 
 Timber.d("Youngest participant %s", 
 participant.getName()));


Slide 76

Slide 76 text

Find the youngest participants
 .parallelStream()
 .min(Comparator.comparingInt(
 Participant::getAge))
 .ifPresent(
 participant -> 
 Timber.d("Youngest participant %s", 
 participant.getName()));


Slide 77

Slide 77 text

Map Set names =
 participants.stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toSet());

Slide 78

Slide 78 text

Map Set names =
 participants.stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toSet());

Slide 79

Slide 79 text

Map Set names =
 participants.stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toSet());

Slide 80

Slide 80 text

Map SortedSet names =
 participants.stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toCollection(TreeSet::new));

Slide 81

Slide 81 text

Map SortedSet names =
 participants.stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toCollection(TreeSet::new));

Slide 82

Slide 82 text

Streams are lazy • The intermediate operations are always lazy • The “terminal” operations produce values or side- effects

Slide 83

Slide 83 text

Map SortedSet names =
 participants
 .stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toCollection(TreeSet::new));

Slide 84

Slide 84 text

Map SortedSet names =
 participants
 .stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toCollection(TreeSet::new));

Slide 85

Slide 85 text

Map SortedSet names =
 participants
 .stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toCollection(TreeSet::new));

Slide 86

Slide 86 text

Map SortedSet names =
 participants
 .stream()
 .map(Participant::getName)
 .sorted()
 .collect(Collectors.toCollection(TreeSet::new));

Slide 87

Slide 87 text

Map SortedSet names =
 participants
 .stream()
 .map(Participant::getName)
 .sorted()
 .limit(2)
 .collect(Collectors.toCollection(TreeSet::new));

Slide 88

Slide 88 text

Nougat only features • Streams • Default and static interface methods • Repeatable annotations

Slide 89

Slide 89 text

Default methods

Slide 90

Slide 90 text

Default methods How do streams work?

Slide 91

Slide 91 text

Default methods • How to build “streams” without breaking all custom collections? • Collection interface adds: • boolean removeIf(Predicate super E> filter) • Spliterator spliterator() • Stream stream() • Stream parallelStream()

Slide 92

Slide 92 text

Default methods • default boolean removeIf(Predicate super E> filter) • default Spliterator spliterator() • default Stream stream() • default Stream parallelStream()

Slide 93

Slide 93 text

Default methods Enables you to add new (default) implementations to interfaces so implementing classes don’t need to change

Slide 94

Slide 94 text

Collection @Override
 default Spliterator spliterator() {
 return Spliterators.spliterator(this, 0);
 }
 default Stream stream() {
 return StreamSupport.stream(spliterator(), false);
 }

Slide 95

Slide 95 text

Implementing classes • When you implement an interface that contains a default method, you can do the following: • Not mention the default method at all, which lets your implementation use the default method • Override the default method • Reuse the default method implementation using super

Slide 96

Slide 96 text

Implementing classes • Not mention the default method at all, which lets your implementation use the default method

Slide 97

Slide 97 text

Implementing classes • Not mention the default method at all, which lets your implementation use the default method class FancyList implements Collection

Slide 98

Slide 98 text

Implementing classes • Override the default method

Slide 99

Slide 99 text

Implementing classes • Override the default method class FancyList implements Collection @Override
 public Stream stream() {
 return ….. 
 }

Slide 100

Slide 100 text

Implementing classes • Reuse the default method implementation using super

Slide 101

Slide 101 text

Implementing classes • Reuse the default method implementation using super class FancyList implements Collection @Override
 Stream stream() {
 // ……
 return super.stream();
 }

Slide 102

Slide 102 text

Extending interface • When you extend an interface that contains a default method, you can do the following: • Not mention the default method at all, which lets your extended interface inherit the default method • Redeclare the default method, which makes it abstract • Redefine the default method, which overrides it

Slide 103

Slide 103 text

Extending interface • Not mention the default method at all, which lets your extended interface inherit the default method

Slide 104

Slide 104 text

Extending interface • Not mention the default method at all, which lets your extended interface inherit the default method interface Set extends Collection {
 ….
 }

Slide 105

Slide 105 text

Extending interface • Redeclare the default method, which makes it abstract

Slide 106

Slide 106 text

Extending interface • Redeclare the default method, which makes it abstract
 
 interface FancySet extends Collection {
 ….
 Stream stream();
 }

Slide 107

Slide 107 text

Extending interface • Redefine the default method, which overrides it

Slide 108

Slide 108 text

Extending interface • Redefine the default method, which overrides it interface Set extends Collection {
 ….
 @Override default Spliterator spliterator() {
 return Spliterators.spliterator(this, Spliterator.DISTINCT);
 }
 }

Slide 109

Slide 109 text

Multiple inheritance? public interface A {
 default void foo() {
 Timber.d(“Calling A.foo()");
 }
 }
 
 
 
 
 
 
 public class ProblematicClass implements A, B {
 //…..
 } public interface B {
 default void foo() {
 Timber.d(“Calling B.foo()");
 }
 }

Slide 110

Slide 110 text

Multiple inheritance? public interface A {
 default void foo() {
 Timber.d(“Calling A.foo()");
 }
 }
 
 
 
 
 
 
 public class ProblematicClass implements A, B {
 //…..
 } public interface B {
 default void foo() {
 Timber.d(“Calling B.foo()");
 }
 }

Slide 111

Slide 111 text

Multiple inheritance public class ProblematicClass implements A, B { } // error: class ProblematicClass inherits unrelated defaults for foo() from types A and B

Slide 112

Slide 112 text

Multiple inheritance public class ProblematicClass implements A, B { } // error: class ProblematicClass inherits unrelated defaults for foo() from types A and B

Slide 113

Slide 113 text

Multiple inheritance public class ProblematicClass implements A, B { @Override public void foo() { } }

Slide 114

Slide 114 text

Multiple inheritance public class ProblematicClass implements A, B { @Override public void foo() { A.super.foo(); B.super.foo(); } }

Slide 115

Slide 115 text

Instances methods vs default methods public class Horse { public String identifyMyself() { return "I am a horse."; } } public interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } public interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } }

Slide 116

Slide 116 text

Instances methods vs default methods public class Horse { public String identifyMyself() { return "I am a horse."; } } public interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } public interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } }

Slide 117

Slide 117 text

Instances methods vs default methods public class Horse { public String identifyMyself() { return "I am a horse."; } } public interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } public interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } }

Slide 118

Slide 118 text

Instances methods vs default methods public class Horse { public String identifyMyself() { return "I am a horse."; } } public interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } public interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } }

Slide 119

Slide 119 text

Instances methods vs default methods public class Horse { public String identifyMyself() { return "I am a horse."; } } public interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } public interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } }

Slide 120

Slide 120 text

Instances methods vs default methods • Instance methods are preferred over interface default methods • The method Pegasus.identifyMyself returns the string I am a horse.

Slide 121

Slide 121 text

Static methods • Comparator gains:
 
 public static > Comparator reverseOrder() {
 return Collections.reverseOrder();
 }

Slide 122

Slide 122 text

Nougat only features • Streams • Default and static interface methods • Repeatable annotations

Slide 123

Slide 123 text

Repeatable annotations You may now create annotations that can be repeated

Slide 124

Slide 124 text

Example @Schedule(dayOfMonth="last")
 @Schedule(dayOfWeek="Fri", hour="23")
 public void doPeriodicCleanup() { ... }

Slide 125

Slide 125 text

How-to • Declare the annotation as repeatable • Declare a containing annotation type • See: https://docs.oracle.com/javase/tutorial/java/ annotations/repeating.html

Slide 126

Slide 126 text

Pre-N alternatives

Slide 127

Slide 127 text

Alternative options • Lambdas -> Retrolambda • Streams -> Lightweight Stream API

Slide 128

Slide 128 text

Build setup

Slide 129

Slide 129 text

Requirements • This applies for all Java 8 features • Requirements: • Use Jack & Jill • Set language compatibility • Android Studio 2.1+ • Build tools 21.1.1+

Slide 130

Slide 130 text

A bit about Jack • Jack is a new Android toolchain • Compiles Java source into Android dex bytecode • Replaces the previous toolchain • javac, ProGuard, jarjar, dx etc.

Slide 131

Slide 131 text

A bit about Jack

Slide 132

Slide 132 text

What’s Jill? • Jill translates the existing .jar libraries into the new library format

Slide 133

Slide 133 text

A bit about Jill

Slide 134

Slide 134 text

How to setup • Instructions at : https://developer.android.com/ guide/platform/j8-jack.html

Slide 135

Slide 135 text

Annotation processor • If you’re using Dagger, Butterknife etc. apply plugin: 'com.neenbedankt.android-apt'
 apt 'com.google.dagger:dagger-compiler:2.2'

Slide 136

Slide 136 text

Annotation processor annotationProcessor ‘com.google.dagger:dagger-compiler:2.2’

Slide 137

Slide 137 text

Annotation processor • Guide: https://bitbucket.org/hvisser/android-apt/ wiki/Migration

Slide 138

Slide 138 text

Known issues • Jack does not generate intermediate class files when compiling an app, so it breaks some tools • Instant run doesn’t work with Jack • Lint that operates on class files • JaCoCo instrumentation (now fixed) • Possible Kotlin issues

Slide 139

Slide 139 text

Known issues • Updated list: https://source.android.com/source/ known-issues.html • The one under Java 8 features doesn’t seem to be updated • File bugs: http://tools.android.com/filing-bugs

Slide 140

Slide 140 text

Resources

Slide 141

Slide 141 text

Links — Lambdas • Many lambda examples: docs.oracle.com/javase/ tutorial/java/javaOO/lambdaexpressions.html • Lambda tutorial: https://github.com/ AdoptOpenJDK/lambda-tutorial • Official docs on Streams: http://docs.oracle.com/ javase/tutorial/collections/streams/ • Streams tutorial: http://blog.hartveld.com/2013/03/ jdk-8-33-stream-api.html

Slide 142

Slide 142 text

Other talks • Exploring Java’s Hidden Costs (@JakeWharton) • Jack and Jill build system (Eric Lafortune) • API Design With Java 8 Lambda and Streams (@stuartmarks & @BrianGoetz)

Slide 143

Slide 143 text

Thank you http://bit.do/droidcon-java8
 https://github.com/anothem/ java8-android