Pro Yearly is on sale from $80 to $50! »

Java 7+8

6acd3df818349485f3942b5c6d16247a?s=47 Youri Ackx
February 08, 2015

Java 7+8

Principales nouveautés depuis... Java 6.

6acd3df818349485f3942b5c6d16247a?s=128

Youri Ackx

February 08, 2015
Tweet

Transcript

  1. Java 7+8 NASCA Pierre Verhaeghe Youri Ackx

  2. Java 6 :-/ Qu’est-ce qui vous dérange dans Java 6

    ? Qu’est-ce qui vous ferait plaisir ?
  3. None
  4. Java 7 Rien d’extraordinaire mais c’est déjà ça

  5. String in switch statement @Test public void test_java7() { String

    artist = "David Bowie"; switch (artist) { case "Michael Jackson": System.out.println("I'm a pop singer."); break; case "David Bowie": System.out.println("I'm a rock singer."); break; case "Frank Sinatra": System.out.println("I'm a jazz singer."); break; default: System.out.println("I'm not a great singer."); break; } }
  6. Diamond operator @Test public void test_java6Example(){ Map<String, List<Node>> trades =

    new HashMap<String, List<Node>> (); System.out.println(trades.size()); } @Test public void test_java7Example(){ Map<String, List<Node>> trades = new HashMap<> (); System.out.println(trades.size()); }
  7. Automatic resource management @Test public void test_streamResourceJava7() throws IOException{ //FileOuputStream

    implements AutoCloseable interface. //factory.create("output.txt") = new FileOutputStream("output.txt"); try (FileOutputStream out = factory.create("output.txt");) { } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } verify(stream, times(1)).close(); } C’est la syntaxe
  8. Literals with underscores @Test public void test(){ int millionJava6 =

    1000000; int millionJava7 = 1_000_000; Assert.assertEquals("Million expected.", millionJava7 , millionJava6); }
  9. Multicatch @Test public void test_multipleExceptionsJava7(){ try { generateExceptions(); } catch

    (IOException | SQLException e) { e.printStackTrace(); } }
  10. NIO 2.0 Nouvelle API : java.nio.* • Path : représentation

    d’un chemin relatif/absolu • FileSystem • Classes utilitaires : Paths, Files, FileSystems • WatchService
  11. NIO 2.0 exemples //java6 read file FileReader fr = null;

    BufferedReader reader = null; try { fr = new FileReader(SOURCE_FILE); reader = new BufferedReader(fr); String line; line = reader.readLine(); while ( line != null ) { System.out.println(line); line = reader.readLine(); } } //java 7 read small file List<String> lines = Files.readAllLines(SOURCE_FILE.toPath(), Charset.forName("UTF-8")); for (String line : lines){ System.out.println(line); }
  12. NIO 2.0 exemples @Test public void test_fileFilter(){ PathMatcher matcher =

    FileSystems.getDefault().getPathMatcher("glob:**/*.txt"); //regex can also be used Path path = SOURCE_FILE.toPath(); if (matcher.matches(path)) { System.out.println(path); } } @Test public void test_copyFileJava7() throws IOException{ Files.copy(SOURCE_FILE.toPath(), TARGET_FILE.toPath()); Assert.assertTrue(TARGET_FILE.exists()); }
  13. Java 8 Pour faire comme les hipsters

  14. Imperative vs functional programming

  15. Imperative programming : programmes basés sur des états mémoires et

    composés d’instructions qui changent ces états à l’exécution. List<Student> students = … List<Student> tenOverFifty = new ArrayList<Student>(); int count = 0; for (Student student : students) { if (student.getScore() > 50) { tenOverFifty.add(student); count++; if (count >= 10) break; } } return tenOverFifty;
  16. Functional programming : programmes composés d’ un ensemble d’expressions évaluées

    à l’exécution. List<Student> students = … return students.stream() .filter(s -> s.getScore() > 50) .limit(10); Avantage : lisibilité, non lié à un état du système, ...
  17. Avant Java 8, était-il possible de faire de la programmation

    fonctionnelle?
  18. Guava, Functional java, Jambda, ... Exemple : public List<Tax> getExtraTax()

    { return Lists.newArrayList(filter(getTaxes(), Taxes.Predicates.YEARLY)); }
  19. Lambdas Méthodes anonymes visant à réduire la verbosité des classes

    anonymes
  20. Lambdas (Object o) -> o.toString() Object::toString (Person p) -> p.getName().equals(name)

    p -> p.getName().equals(name) Method reference Type inference
  21. Lambdas JButton btn = new JButton(); final PrintStream pStream =

    ...; btn.addActionListener(new ActionListener { @Override public void actionPerformed(ActionEvent e) { pStream.println("Button Clicked!"); } }); JButton btn = new JButton(); final PrintStream pStream = ...; btn.addActionListener(e -> pStream.println("Button Clicked!"));
  22. java.util.stream filter / map / reduce

  23. java.util.streams List<Student> students = …; Stream stream = students.stream(); Stream

    parallelstream = students.parallelStream(); • Traversés une seule fois • Inifinis • Lazy
  24. java.util.streams - Sources Collections Set<Student> students = …; Stream stream

    = students.stream(); Generators Random random = new Random(); Stream randomNumbers = Stream.generate(random::nextInt); From other streams Stream newStream = Stream.concat(stream, randomNumbers);
  25. java.util.streams - Intermediate operations .filter exclude all elements that don’t

    match a Predicate .map transform element using a Function .flatMap transform each element into 0+ elements by way of another Stream .peek perform some action on each element .distinct exclude duplicates (equals()) .sorted ordered elements (Comparator) .limit max numbers of elements .substream range by index of elements
  26. java.util.streams - Pre-Java8 List<Student> students = … int highScore2014 =

    Integer.MIN_VALUE; for (Student student : students) { if (student.getGradYear() == 2014 && student.getScore() > highScore2014) { highScore2014 = student.getScore(); } } return highScore2014;
  27. java.util.streams - Java8 List<Student> students = … return students.stream() .filter(Student

    s -> s.getGradYear() == 2014) .map(Student s -> s.getScore()) .max();
  28. java.util.streams - Java8 List<Student> students = … return students.stream() .filter(s

    -> s.getGradYear() == 2014) .map(s -> s.getScore()) .max(); Student s -> Type inference
  29. java.util.streams - Pre-Java8 List<Student> students = … List<Student> tenOverFifty =

    new ArrayList<Student>(); int count = 0; for (Student student : students) { if (student.getScore() > 50) { tenOverFifty.add(student); count++; if (count >= 10) break; } } return tenOverFifty;
  30. java.util.streams - Java8 List<Student> students = … return students.stream() .filter(s

    -> s.getScore() > 50) .limit(10);
  31. java.util.streams - Terminating operations reducers reduce(), count(), findAny(), findFirst() collectors

    collect() forEach iterators
  32. java.util.streams - Natural numbers IntStream natural = IntStream.iterate(0, i ->

    i + 1); natural .limit(10) .forEach(System.out::println); seed IntUnaryOperator
  33. Functional Interfaces Single Abstract Method Type

  34. Functional Interfaces - Example @FunctionalInterface public interface Runnable { public

    abstract void run(); } Runnable r = () -> System.out.println("Hello World!"); Historically have used single method interfaces to represent functions: Runnable, Comparator, ActionListener
  35. java.util.function Predicate<T> - a boolean-valued property of an object Consumer<T>

    - an action to be performed on an object Function<T, R> - a function transforming a T to a R Supplier<T> - provide an instance of a T (such as a factory) UnaryOperator<T> - a function from T to T BinaryOperator<T> - a function from (T, T) to T
  36. java.util.function - Example Collections.sort(people, new Comparator<Person>() { @Override public int

    compare(Person x, Person y) { return x.getLastName().compareTo(y.getLastName()); } } Collections.sort(people, Comparators.comparing(Person::getLastName()); Method reference
  37. java.util.function - Method references A static method (ClassName::methName) An instance

    method of a particular object (instanceRef::methName) A super method of a particular object (super::methName) An instance method of an arbitrary object of a particular type (ClassName::methName) A class constructor reference (ClassName::new) An array constructor reference (TypeName[]::new)
  38. Default methods Ajoute un comportement par défaut à une interface

  39. Default methods - Pourquoi Java 8 offre les lambdas et

    on veut les utiliser : List<?> list = ...; list.forEach(...); // lamdba code N’existe pas sur java.util.list. Ajouter des méthodes à l’ interface casserait les implémentations existantes. = Default methods = Defender methods Rétrocompatible : on peut ajouter une méthode par défaut sans casser l’existant. Cela réduit aussi la qté de code.
  40. Default methods - Exemple public interface FlyingAbility { default void

    fly() { System.out.println(“I’m flying”); } } public class Duck implements FlyingAbility { } Duck duck = new Duck(); duck.fly();
  41. Default methods - Exemple public interface FlyingAbility { default void

    fly() { System.out.println(“I’m flying”); } } public interface SwimmingAbility { default void swim() { System.out.println(“I’m swimming”); } } public class Duck implements FlyingAbility, SwimmingAbility { } Duck duck = new Duck(); duck.fly(); duck.swim();
  42. Default methods - Exemple public interface A { default void

    foo() { System.out.println(“A foo”); } } public interface B { default void foo() { System.out.println(“B foo”); } } public class Duck implements A, B { } Et ça compile?
  43. java.time Il était temps

  44. java.time • Immutability -> multi-threading • Séparation des différentes notions

    : Date, Time, DateTime, Timestamp, Timezone, Period, Duration, Instant • Clareté : méthodes définies clairement et uniformément (plus de différences entre java.util.Date et java.sql.Date) • Méthodes utilitaires : plus, minus, format, … • Extensible : ouvert à d’autres systèmes de calendriers • Gestion en standard de l’i18n
  45. java.time - Current time Clock clockUTC = Clock.systemUTC(); Clock clockDefault

    = Clock.systemDefaultZone();
  46. java.time - Timezones ZoneId zone = ZoneId.systemDefault(); ZoneId zoneBerlin =

    ZoneId.of("Europe/Berlin"); Clock clock = Clock.system(zoneBerlin);
  47. java.time - Human readable class LocalDate { public static LocalDate

    now() { ... } public static LocalDate now(ZoneId zone) { ... } public static LocalDate now(Clock clock) { ... } } LocalDate date = LocalDate.now(); System.out.printf("%s-%s-%s", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
  48. java.time - Calculations LocalTime lt = LocalTime.now(); lt.plus(5, ChronoUnit.HOURS); lt.plusHours(5);

    Duration dur = Duration.of(5, ChronoUnit.HOURS); lt.plus(dur);
  49. Accumulators

  50. Accumulators - Exemples DoubleAccumulator da = new DoubleAccumulator((x,y) -> x

    + y, 0.0); List<Double> doubles = Arrays.asList(1.0, 2.0, 3.0, 4.0, 10.0); doubles.forEach(da::accumulate); System.out.println("Result: " + da.doubleValue()); 20 LongAdder la = new LongAdder(); List<long> longs = Arrays.asList(10, 20, 30, 40, 100); longs.forEach(la::accumulate); System.out.println("Result: " + la.longValue()); 200 Utilité : compteur de statistique, remplacement de la classe AtomicInt, AtomicLong, ...
  51. java.util.Optional Null-safe navigation

  52. java.util.Optional - pre-Java8 String version = computer.getSoundcard().getUSB().getVersion(); return version !=

    null ? version : “UNKNOWN”;
  53. java.util.Optional - pre-Java8 String version = “UNKNOWN”; if (computer !=

    null) { Soundcard soundcard = computer.getSoundCard(); if (soundcard != null) { Usb usb = soundcard.getUsb(); if (usb != null) { version = usb.getVersion(); } } } return version;
  54. java.util.Optional - Groovy return computer?.getSoundcard()?.getUSB()?.getVersion() ?: "UNKNOWN"; null-safe navigation Elvis

    operator
  55. java.util.Optional - Java8 public class Computer { private Optional<Soundcard> soundcard;

    public Optional<Soundcard> getSoundcard() { ... } } public class Soundcard { private Optional<USB> usb; public Optional<USB> getUSB() { ... } } public class USB{ public String getVersion(){ ... } } String version = computer.flatMap(Computer::getSoundcard) .flatMap(Soundcard::getUSB) .map(USB::getVersion) .orElse("UNKNOWN");
  56. None
  57. java.util.Optional - c0wb0y String version = null; try { version

    = computer.getSoundcard().getUSB().getVersion(); } catch (NullPointerException npe) { version = “UNKNOWN”; } return version;
  58. Cette œuvre est mise à disposition selon les termes de

    la Licence Creative Commons Attribution - Partage dans les Mêmes Conditions 4.0 International.
  59. Youri Ackx Agile and Pragmatic Java/Grails Developer @YouriAckx

  60. Pierre Verhaeghe