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

Java 7+8

Avatar for Youri Ackx Youri Ackx
February 08, 2015

Java 7+8

Principales nouveautés depuis... Java 6.

Avatar for Youri Ackx

Youri Ackx

February 08, 2015
Tweet

More Decks by Youri Ackx

Other Decks in Technology

Transcript

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

    ? Qu’est-ce qui vous ferait plaisir ?
  2. 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; } }
  3. 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()); }
  4. 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
  5. Literals with underscores @Test public void test(){ int millionJava6 =

    1000000; int millionJava7 = 1_000_000; Assert.assertEquals("Million expected.", millionJava7 , millionJava6); }
  6. NIO 2.0 Nouvelle API : java.nio.* • Path : représentation

    d’un chemin relatif/absolu • FileSystem • Classes utilitaires : Paths, Files, FileSystems • WatchService
  7. 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); }
  8. 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()); }
  9. 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;
  10. 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, ...
  11. Guava, Functional java, Jambda, ... Exemple : public List<Tax> getExtraTax()

    { return Lists.newArrayList(filter(getTaxes(), Taxes.Predicates.YEARLY)); }
  12. Lambdas (Object o) -> o.toString() Object::toString (Person p) -> p.getName().equals(name)

    p -> p.getName().equals(name) Method reference Type inference
  13. 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!"));
  14. java.util.streams List<Student> students = …; Stream stream = students.stream(); Stream

    parallelstream = students.parallelStream(); • Traversés une seule fois • Inifinis • Lazy
  15. 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);
  16. 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
  17. 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;
  18. java.util.streams - Java8 List<Student> students = … return students.stream() .filter(Student

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

    -> s.getGradYear() == 2014) .map(s -> s.getScore()) .max(); Student s -> Type inference
  20. 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;
  21. java.util.streams - Natural numbers IntStream natural = IntStream.iterate(0, i ->

    i + 1); natural .limit(10) .forEach(System.out::println); seed IntUnaryOperator
  22. 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
  23. 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
  24. 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
  25. 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)
  26. 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.
  27. 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();
  28. 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();
  29. 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?
  30. 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
  31. java.time - Timezones ZoneId zone = ZoneId.systemDefault(); ZoneId zoneBerlin =

    ZoneId.of("Europe/Berlin"); Clock clock = Clock.system(zoneBerlin);
  32. 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());
  33. 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, ...
  34. 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;
  35. 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");
  36. java.util.Optional - c0wb0y String version = null; try { version

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

    la Licence Creative Commons Attribution - Partage dans les Mêmes Conditions 4.0 International.