Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java 8 Language Additions

Java 8 Language Additions

Describes new Java 8 features such as Lambdas. Method References, Default Methods etc.

Dmitry Buzdin

April 03, 2014
Tweet

More Decks by Dmitry Buzdin

Other Decks in Programming

Transcript

  1. Significant Changes • Lambda Expressions • Method References • Default

    Methods • Type Annotations • Streams API http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
  2. Before Java 8 • Everything is a class (except primitives)

    • Class is a “heavyweight” construct • Composition is hard
  3. Use Cases • Reusable composite constructs needed: • GUI Listeners

    • Command pattern • Event processing • Asynchronous programming
  4. Async executeAsync(“param”, new Callback() { @Override onSuccess(String result1) { executeAsync(result1,

    new Callback()) { @Override onSuccess(Object result2) { System.out.println(result); } } } })
  5. Anonymous Classes • Hard to read • New objects are

    created in heap • Compiler creates additional class files
  6. Lambda Expression “Function, defined and called without being bound to

    identifier” Relates to Functional Programming
  7. 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#
  8. 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/
  9. 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/
  10. The Question for Java 8 • How to add Lambdas

    but • remain Java • be backward compatible • reuse existing libraries
  11. Lambdas in Java 8 (Integer x, Integer y) -> x

    + y (Integer x, Integer y) -> { r = x + y; System.out.println(r); return r; }
  12. 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
  13. 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
  14. Existing JDK FIs Comparator { boolean compare(T x, T y);

    } Runnable { void run(); } Callable { T call(); } PropertyChangeListener { void propertyChange(PropertyChangeEvent evt) }
  15. New JDK FIs java.util.function package contains 44 new functional interfaces

    Consumer, Function, Predicate, Supplier, Operator and versions for all primitives
  16. 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
  17. 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
  18. 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
  19. Type Inference List<Integer> list = new ArrayList<>(); ! Collections.sort(list, (Integer

    x, Integer y) -> x - y); Collections.sort(list, (x, y) -> x - y);
  20. So what? • Finally, Java is not worse than Ruby!

    • Less coding • Static type compiler checks
  21. 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?
  22. Method Reference MyCoolClass::method There are four different types of method

    references object::method Like C method pointer, but safer
  23. 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);
  24. 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);
  25. 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);
  26. Constructor List list1 = createNewObject( new Supplier<List>() { @Override public

    List get() { return new ArrayList<>(); } }); List list2 = createNewObject(ArrayList::new);
  27. Recap • It is possible to reference existing methods instead

    of writing lambda expressions • Reuse of existing pre Java 8 code • Different type of references
  28. Java 7 Model • Single inheritance • Multiple interfaces •

    No method implementations on interface • All methods on interfaces are abstract
  29. Default Methods public interface MyInterface { ! void apply(); !

    default void apply2() { // do some work } ! }
  30. Extending Interfaces public class Klass implements MyInterface { @Override void

    apply() { ... } } ! Klass k = new Klass(); klass.apply(); klass.apply2();
  31. Multiple Interfaces public class Klass implements CanWalk, CanFly, CanSwim, CanDrive

    { ... } ! Klass k = new Klass(); klass.walk(); klass.eat(); klass.fly();
  32. 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
  33. 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(); } }
  34. Static Methods public static interface MyInterface { ! public static

    String wrap(String s) { return "{" + s + "}"; } ! void apply(); ! } Nice for utility methods
  35. Factory + Interface • Could be finally combined • Shared

    functions on the interface • Better Encapsulation
  36. Factory on Interface public interface Gadget { public static Gadget

    create(String id) { return new GadgetImpl(); } ! void start(); } ! Gadget gadget = Gadget.create(“x”); gadget.start();
  37. 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);
  38. 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
  39. 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
  40. 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"
  41. 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)