Share
Embed
Java 8 on Android
Video: https://skillsmatter.com/skillscasts/8696-java-8-on-android
Java 8 features have finally made their way to the Android world and if you haven't been trying them, you are missing out. This talk is all about getting you up to speed on all of these new features and how to use them. It will be a great primer if you've never looked into them or a refresher if it's been a while.
Alex Florescu
October 26, 2016
Transcript
143 slides
-
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 -
API support • Official website “Also available on API level
23 and lower” • Google I/O 2016 “Backward compatible with Gingerbread” -
Functional interface • Has exactly one abstract method • Can
annotate with @FunctionalInterface • Not necessary for using lambdas with it -
Functional interface • A lot of standard ones added in
java.util.function • Consumer<T> — an operation that accepts a single input argument and returns no result • Function<T,R> — a function that accepts one argument and produces a result • Predicate<T> — a predicate (boolean-valued function) of one argument • Supplier<T> — a supplier of results -
Setting listener button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v)
{ Snackbar.make(mainPanel, "Click listener triggered", Snackbar.LENGTH_SHORT).show(); } }); -
Setting listener button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v)
{ Snackbar.make(mainPanel, "Click listener triggered", Snackbar.LENGTH_SHORT).show(); } }); -
Setting listener button1.setOnClickListener(v -> Snackbar.make(mainPanel, "Click listener triggered",
Snackbar.LENGTH_SHORT).show()); -
Setting listener button1.setOnClickListener(v -> Snackbar.make(mainPanel, "Click listener triggered",
Snackbar.LENGTH_SHORT).show()); -
Lambda examples // Lambda with no parameters Runnable r2 =
() -> Timber.d("Lambda test"); -
Example with params participantRedList.setAdapter( new ParticipantAdapter( filterParticipants(participants, new FilterCondition<Participant>()
{ @Override public boolean accept(Participant candidate) { return candidate.getTeamColour() == TeamColour.RED; } }))); -
Example with params participantRedList.setAdapter( new ParticipantAdapter( filterParticipants(participants, new FilterCondition<Participant>()
{ @Override public boolean accept(Participant candidate) { return candidate.getTeamColour() == TeamColour.RED; } }))); -
Example with params participantRedList.setAdapter( new ParticipantAdapter( filterParticipants(participants, new FilterCondition<Participant>()
{ @Override public boolean accept(Participant candidate) { return candidate.getTeamColour() == TeamColour.RED; } }))); -
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; } -
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; } -
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; } -
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; } -
Example Collections.sort(participants, new Comparator<Participant>() { @Override public int compare(Participant
p1, Participant p2) { return Integer.compare(p1.getAge(), p2.getAge()); } }); -
Example public final class Participant { …. public static int
compareByAge(Participant a, Participant b) { return Integer.compare(a.getAge(), b.getAge()); } …. } -
Example public final class Participant { …. public static int
compareByAge(Participant a, Participant b) { return Integer.compare(a.getAge(), b.getAge()); } …. } -
Example Collections.sort(participants, new Comparator<Participant>() { @Override public int compare(Participant
p1, Participant p2) { return Participant.compareByAge(p1,p2); } }); -
From Collections.sort(participants, new Comparator<Participant>() { @Override public int compare(Participant
p1, Participant p2) { return Participant.compareByAge(p1,p2); } }); -
Syntax • Reference to a static method (s) -> String.valueOf(s)
String::valueOf -
Syntax • Reference to an instance method of a particular
object (o) -> o.toString() -
Syntax • Reference to an instance method of a particular
object (o) -> o.toString() o::toString -
Syntax • Reference to an instance method of an arbitrary
object of a particular type Arrays.sort((a,b) -> a.compareToIgnoreCase(b)) -
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) -
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) -
Method count • Exploring Java’s Hidden Costs (Jake Wharton) •
23:30 — Lambdas -
Comparison with Kotlin • Claims no increase in method count,
bytecode inserted directly (see post) -
Annotations before Java 8 • Method: @Override void onCreate()… •
Class: @RunWith(JUnit4Runner.class) public class TestDoggieTreats {… • Parameters, return values @NonNull String prepareText(@Nullable input); -
Type annotations • Anywhere you use a type • Class
instantiation: new @Interned MyObject(); • Type cast: myString = (@NonNull String) str; • Implements clause: class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... } • Throws: void monitorTemperature() throws @Critical TemperatureException { ... } -
Type annotations • Anywhere you use a type • Class
instantiation: new @Interned MyObject(); • Type cast: myString = (@NonNull String) str; • Implements clause: class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... } • Throws: void monitorTemperature() throws @Critical TemperatureException { ... } -
Requirements • Using the Jack compiler • Setting language compatibility
to 1.8 • (more on that later) -
Nougat only features • Streams • Default and static interface
methods • Repeatable annotations -
Streams A new abstraction that lets you process data in
a declarative way -
Streams Data manipulation like you always dreamed of. Can filter,
map & reduce while being traversed, sequentially or in parallel. -
Example public interface FilterCondition<T> { boolean accept(T candidate); } List<Participant>
filter(List<Participant> participants, FilterCondition<Participant> filterCondition) -
Example List<Participant> output = new ArrayList<>(); for (Participant participant
: participants) { if (filterCondition.accept(participant)) { output.add(participant); } } return output; -
Example List<Participant> filter( List<Participant> participants, Predicate<Participant> predicate) return participants.stream()
.filter(predicate) .collect(Collectors.toList()); -
Example List<Participant> filter( List<Participant> participants, Predicate<Participant> predicate) return participants.stream()
.filter(predicate) .collect(Collectors.toList()); -
Find the youngest participants .stream() .min(Comparator.comparingInt( Participant::getAge)) .ifPresent( participant ->
Timber.d("Youngest participant %s", participant.getName())); -
Find the youngest participants .stream() .min(Comparator.comparingInt( Participant::getAge)) .ifPresent( participant ->
Timber.d("Youngest participant %s", participant.getName())); -
Find the youngest participants .stream() .min(Comparator.comparingInt( Participant::getAge)) .ifPresent( participant ->
Timber.d("Youngest participant %s", participant.getName())); -
Find the youngest participants .stream() .min(Comparator.comparingInt( Participant::getAge)) .ifPresent( participant ->
Timber.d("Youngest participant %s", participant.getName())); -
Find the youngest participants .parallelStream() .min(Comparator.comparingInt( Participant::getAge)) .ifPresent( participant ->
Timber.d("Youngest participant %s", participant.getName())); -
Streams are lazy • The intermediate operations are always lazy
• The “terminal” operations produce values or side- effects -
Nougat only features • Streams • Default and static interface
methods • Repeatable annotations -
Default methods • How to build “streams” without breaking all
custom collections? • Collection interface adds: • boolean removeIf(Predicate<? super E> filter) • Spliterator<E> spliterator() • Stream<E> stream() • Stream<E> parallelStream() -
Default methods • default boolean removeIf(Predicate<? super E> filter) •
default Spliterator<E> spliterator() • default Stream<E> stream() • default Stream<E> parallelStream() -
Default methods Enables you to add new (default) implementations to
interfaces so implementing classes don’t need to change -
Collection @Override default Spliterator<E> spliterator() { return Spliterators.spliterator(this, 0); }
default Stream<E> stream() { return StreamSupport.stream(spliterator(), false); } -
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 -
Implementing classes • Not mention the default method at all,
which lets your implementation use the default method -
Implementing classes • Not mention the default method at all,
which lets your implementation use the default method class FancyList<E> implements Collection<E> -
Implementing classes • Override the default method class FancyList<E> implements
Collection<E> @Override public Stream<E> stream() { return ….. } -
Implementing classes • Reuse the default method implementation using super
class FancyList<E> implements Collection<E> @Override Stream<E> stream() { // …… return super.stream(); } -
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 -
Extending interface • Not mention the default method at all,
which lets your extended interface inherit the default method -
Extending interface • Not mention the default method at all,
which lets your extended interface inherit the default method interface Set<E> extends Collection<E> { …. } -
Extending interface • Redeclare the default method, which makes it
abstract interface FancySet<E> extends Collection<E> { …. Stream<E> stream(); } -
Extending interface • Redefine the default method, which overrides it
interface Set<E> extends Collection<E> { …. @Override default Spliterator<E> spliterator() { return Spliterators.spliterator(this, Spliterator.DISTINCT); } } -
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()"); } } -
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()"); } } -
Multiple inheritance public class ProblematicClass implements A, B { }
// error: class ProblematicClass inherits unrelated defaults for foo() from types A and B -
Multiple inheritance public class ProblematicClass implements A, B { }
// error: class ProblematicClass inherits unrelated defaults for foo() from types A and B -
Multiple inheritance public class ProblematicClass implements A, B { @Override
public void foo() { } } -
Multiple inheritance public class ProblematicClass implements A, B { @Override
public void foo() { A.super.foo(); B.super.foo(); } } -
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()); } } -
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()); } } -
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()); } } -
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()); } } -
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()); } } -
Instances methods vs default methods • Instance methods are preferred
over interface default methods • The method Pegasus.identifyMyself returns the string I am a horse. -
Static methods • Comparator gains: public static <T extends
Comparable<? super T>> Comparator<T> reverseOrder() { return Collections.reverseOrder(); } -
Nougat only features • Streams • Default and static interface
methods • Repeatable annotations -
How-to • Declare the annotation as repeatable • Declare a
containing annotation type • See: https://docs.oracle.com/javase/tutorial/java/ annotations/repeating.html -
Requirements • This applies for all Java 8 features •
Requirements: • Use Jack & Jill • Set language compatibility • Android Studio 2.1+ • Build tools 21.1.1+ -
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. -
What’s Jill? • Jill translates the existing .jar libraries into
the new library format -
Annotation processor • If you’re using Dagger, Butterknife etc. apply
plugin: 'com.neenbedankt.android-apt' apt 'com.google.dagger:dagger-compiler:2.2' -
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 -
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 -
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 -
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)