Share
Embed
Java 8 Language Additions
Describes new Java 8 features such as Lambdas. Method References, Default Methods etc.
Dmitry Buzdin
April 03, 2014
Transcript
68 slides
-
Significant Changes • Lambda Expressions • Method References • Default
Methods • Type Annotations • Streams API http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html -
Before Java 8 • Everything is a class (except primitives)
• Class is a “heavyweight” construct • Composition is hard -
Use Cases • Reusable composite constructs needed: • GUI Listeners
• Command pattern • Event processing • Asynchronous programming -
UI Listener addClickListener(ClickListener listener); ! public interface ClickListener { void
onClick(Widget sender) } -
button.addClickListener(new ClickListener() { public void onClick(Widget sender) { processData(sender.getText()); reportData(sender.getText());
logResults(); } }); Existing Solution Anonymous Class -
Async executeAsync(“param”, new Callback() { @Override onSuccess(String result1) { executeAsync(result1,
new Callback()) { @Override onSuccess(Object result2) { System.out.println(result); } } } }) -
Anonymous Classes • Hard to read • New objects are
created in heap • Compiler creates additional class files -
Lambda Expression “Function, defined and called without being bound to
identifier” Relates to Functional Programming -
In Other Languages Scala Groovy Ruby Python (x: Int, y:
Int) => x + y { int x, int y -> x + y } lambda {|x, y| x + y} lambda x,y: return x * y function (x,y) {return x * y} JavaScript (int x, int y) => x + y C# -
LambdaJ List<Person> buyersSortedByAges = sort( extract( select(sales, having(on(Sale.class).getValue(), greaterThan(50000))) ),
on(Sale.class).getBuyer() ), on(Person.class).getAge()); https://code.google.com/p/lambdaj/ -
Guava List<Integer> integers = Lists.newArrayList(1, 2, 3); Iterables.filter(integers, new Predicate<Integer>()
{ @Override public boolean apply(Integer input) { return input % 2 == 0; } }); https://code.google.com/p/guava-libraries/ -
Time to learn Scala Java is not functional No Lambdas
make me sad Welcome! -
The Question for Java 8 • How to add Lambdas
but • remain Java • be backward compatible • reuse existing libraries -
Lambdas in Java 8 (Integer x, Integer y) -> x
+ y (Integer x, Integer y) -> { r = x + y; System.out.println(r); return r; } -
Where can be used? • Lambdas can be used with
Functional Interfaces • Functional Interface - interface with one abstract method • Existing interfaces can be reused if they satisfy the rules -
Functional Interface @FunctionalInterface public interface ClickHandler { ! void onClick(Widget
widget); ! // Gives compile time error void onDoubleClick(Widget widget); } java: Unexpected @FunctionalInterface annotation lv.jug.java8.Listener is not a functional interface multiple non-overriding abstract methods found in interface lv.jug.java8.Listener -
Existing JDK FIs Comparator { boolean compare(T x, T y);
} Runnable { void run(); } Callable { T call(); } PropertyChangeListener { void propertyChange(PropertyChangeEvent evt) } -
New JDK FIs java.util.function package contains 44 new functional interfaces
Consumer, Function, Predicate, Supplier, Operator and versions for all primitives -
java.util.function • Predicate: A property of the object passed as
argument • Consumer: An action to be performed with the object passed as argument • Function: Transform a T to a U • Supplier: Provide an instance of a T (such as a factory) • UnaryOperator: A unary operator from T -> T • BinaryOperator: A binary operator from (T, T) -> T -
Guava and Lambdas https://code.google.com/p/guava-libraries/wiki/FunctionalExplained ArrayList<Integer> integers = Lists.newArrayList(1, 2, 3);
Iterables.filter(integers, (i) -> i % 2 == 0); Guava has its own Predicate, Supplier, Function etc. Can be used with Lambda syntax -
Scope int f1 = 0; int f2 = 0; !
void lambdaScope(final int p1, String p2) { int i1 = 1; i1++; int i2 = 2; final int i3 = 3; f2 = 4; execute(() -> { // ? }); } this.f1; this.f2; p1; p2; i2; i3 -
Type Inference List<Integer> list = new ArrayList<>(); ! Collections.sort(list, (Integer
x, Integer y) -> x - y); Collections.sort(list, (x, y) -> x - y); -
Compiling Lambdas http://www.takipiblog.com/2014/01/16/compiling-lambda-expressions-scala-vs-java-8/ • Lambdas are compiled as invoke dynamic
calls • No additional class files created • No new objects created -
So what? • Finally, Java is not worse than Ruby!
• Less coding • Static type compiler checks -
What to do with this? void someMethod() { lambda1((arg) ->
process(arg)); lambda2((arg) -> process(arg)); lambda3((arg) -> process(arg)); } Can we simplify this even further? -
Method Reference MyCoolClass::method There are four different types of method
references object::method Like C method pointer, but safer -
Static Method public static int compare(Integer a, Integer b); !
Arrays.sort(array, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return Util.compare(a, b); } }); Arrays.sort(array, Util::compare); -
Instance Method MyClass object = new MyClass(); ! Arrays.sort(array, new
Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return object.reverse(a, b); } }); Arrays.sort(array, object::reverse); -
Arbitrary Object Arrays.sort(array, new Comparator<String>() { @Override public int compare(String
a, String b) { return a.compareToIgnoreCase(b); } }); Arrays.sort(array, String::compareToIgnoreCase); -
Constructor List list1 = createNewObject( new Supplier<List>() { @Override public
List get() { return new ArrayList<>(); } }); List list2 = createNewObject(ArrayList::new); -
New API Possibilities http://benjiweber.co.uk/blog/2013/12/28/typesafe-database-interaction-with-java-8/ Optional<Person> person = from(Person.class) .where(Person::getFirstName) .like("%ji")
.and(Person::getLastName) .equalTo("weber") .select(personMapper, connectionFactory::openConnection); -
Recap • It is possible to reference existing methods instead
of writing lambda expressions • Reuse of existing pre Java 8 code • Different type of references -
Java 7 Model • Single inheritance • Multiple interfaces •
No method implementations on interface • All methods on interfaces are abstract -
Default Methods public interface MyInterface { ! void apply(); !
default void apply2() { // do some work } ! } -
Extending Interfaces public class Klass implements MyInterface { @Override void
apply() { ... } } ! Klass k = new Klass(); klass.apply(); klass.apply2(); -
Multiple Interfaces public class Klass implements CanWalk, CanFly, CanSwim, CanDrive
{ ... } ! Klass k = new Klass(); klass.walk(); klass.eat(); klass.fly(); -
Potential Use • Library API evolution support • Utility methods
shipped with interface • Default method implementations (no more dummy adapters) • Could be used as Traits/Mixins with some hacks -
Evil Traits public interface CanWalk { default void walk() {
((Human) this).leftLeg(); ((Human) this).rightLeg(); } } class Human implements CanWalk, CanSwim public interface CanSwim { default void swim() { ((Human) this).leftHand(); ((Human) this).rightHand(); } } -
Static Methods public static interface MyInterface { ! public static
String wrap(String s) { return "{" + s + "}"; } ! void apply(); ! } Nice for utility methods -
Factory + Interface • Could be finally combined • Shared
functions on the interface • Better Encapsulation -
Factory on Interface public interface Gadget { public static Gadget
create(String id) { return new GadgetImpl(); } ! void start(); } ! Gadget gadget = Gadget.create(“x”); gadget.start(); -
All Together StringProcessor p = new StringProcessor(" sdfsdf "); Function<String,
String> one = String::trim; Function<String, String> two = one.andThen( (s) -> s.replaceAll("s", “") ); String result = p.process(two); System.out.println(result); -
Type Annotations http://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html @NonNull String str; Annotations anywhere you use
a type. Pretty cool for frameworks and tools. -
Repeating Annotations http://docs.oracle.com/javase/tutorial/java/annotations/repeating.html @Schedule(dayOfMonth="last") @Schedule(dayOfWeek="Fri", hour="23") public void doPeriodicCleanup() {
... } @Repeatable(Schedules.class) public @interface Schedule { ... } -
Method Parameter Reflection @Path("/users/{username}") public class UserResource { @GET @Produces("text/xml")
public String getUser( @PathParam("username") String username) { ... } } Before Java 8 impossible to get this name in runtime -
Permanent Generation • Permanent generation was removed • New metaspace
area in native memory • No more OutOfMemory in PermGen • PermSize parameter does nothing http://java.dzone.com/articles/java-8-permgen-metaspace -
Overall Impression “Java 8 has really done a very elegant
job” ““This is the first time we have done a carefully coordinated co-evolution of the JVM, the language, and the libraries all together – and the results still feel like Java,”” “Java SE 8 lands with Lambda expressions making coding easier for multi-core processors" -
Effect on Libraries • Util function libraries • Method references
• Reflection names of parameters • Static and default methods • Standard interfaces in JDK (e.g. Predicate) • Bytecode incompatibility (cyglib, asm)