1 / 22 Modern Java Features for Better Code Florian Hopf, Zenika
2 / 22 Agenda ● Try with Resources ● Optional ● Date and Time API ● Lambda Expressions ● Streams
3 / 22 Try with Resources ● Aka Automatic resource management ● Helps with forgetting closing resources – Files – IO Streams – Database connections – ...
4 / 22 Traditional Approach FileInputStream in = null; try { in = new FileInputStream("some-file.txt"); // do something with in } catch (IOException ex) { // log or throw exception } finally { if (in != null) { try { in.close(); } catch (IOException ex) { // do nothing }
5 / 22 Try with Resources try (FileInputStream in = new FileInputStream("some-file.txt")) { // do something with in } catch(IOException ex) { // log or throw exception }
6 / 22 Try with Resources ● Will work everywhere you would expect it ● Use it whenever you need to close something ● Interface AutoClosable as a marker
7 / 22 Optional ● Can replace working with null values ● Can prevent NullPointerExceptions
8 / 22 Classic null check public void classicNull() { String result = methodThatCanReturnNull(); if (result != null) { System.out.println(result); } else { System.out.println("Missing value"); } } private String methodThatCanReturnNull() { if (something) { return "Hello"; }
9 / 22 Optional public void optional() { Optional<String> result=methodWithOptional(); System.out.println( result.orElse("Missing value")); } private Optional<String> methodWithOptional() { if (something) { return Optional.of("Hello"); } return Optional.empty(); }
10 / 22 Optional Common Methods ● Creating – of, ofNullable, empty ● Checking – isPresent ● Retrieving – get, orElse, map, filter, ...
11 / 22 Optional ● Can be useful as return value from methods ● Semantic meaning: Value can be absent, needs check ● Null has been called “billion dollar mistake” by its inventor
12 / 22 Date and Time API ● Replacement for java.util.Date and Calendar ● Immutable data structures ● Easy manipulation (e.g. date.plusDays(2)) ● Instant: Timestamp ● LocalDate(Time): Date and Time without Timezone ● ZonedDate(Time): Date and Time with Timezones
13 / 22 Lambdas ● New syntax to pass functionality to methods ● Can be used to replace single method interfaces () -> System.out.println("Hello"); (String name) -> System.out.println(name); Arrays.sort(strArray, (String s1, String s2) -> s2.length() - s1.length());
14 / 22 Lambdas ● Method references can be used as lambdas – Special syntax using :: String::trim ● New interfaces for common functionality – Function, Predicate, Supplier, Consumer
15 / 22 Streams ● Functional modification of stream of elements ● map, filter, reduce ● Not related to Java IO-Streams ● Created easily for Collections (List, Set, Map), arrays, File contents, Ranges, ...
16 / 22 Classic approach List<String> fullnameOfMinors = new ArrayList<>(); for (Person person: persons) { if (person.age < 18) { fullnameOfMinors.add(person.name); } }
17 / 22 Streams List<String> fullnameOfMinors = persons.stream() .filter(person -> person.age < 18) .map(person -> person.name) .collect(Collectors.toList());
18 / 22 Streams ● Intermediate operations – map, filter, distinct, limit, sorted, ... ● Terminal operations – collect, forEach, max, min, ...
19 / 22 Streams ● Grouping Map<Integer, List<Person>> personsByAge = persons.stream() .collect(groupingBy(Person::getAge));
20 / 22 Streams ● Sorting by comparator List<Person> personsSortedByAge = persons.stream() .sorted( Comparator.comparing(Person::getAge)) .collect(toList());
21 / 22 Streams ● Building a String list of elements String stringListOfPersons = persons.stream() .map(person -> person.name) .collect(joining(","));
22 / 22 Resources ● https://leanpub.com/whatsnewinjava8/read ● https://zeroturnaround.com/rebellabs/java-8-streams-che

Modern Java Features

  • 1.
    1 / 22 ModernJava Features for Better Code Florian Hopf, Zenika
  • 2.
    2 / 22 Agenda ●Try with Resources ● Optional ● Date and Time API ● Lambda Expressions ● Streams
  • 3.
    3 / 22 Trywith Resources ● Aka Automatic resource management ● Helps with forgetting closing resources – Files – IO Streams – Database connections – ...
  • 4.
    4 / 22 TraditionalApproach FileInputStream in = null; try { in = new FileInputStream("some-file.txt"); // do something with in } catch (IOException ex) { // log or throw exception } finally { if (in != null) { try { in.close(); } catch (IOException ex) { // do nothing }
  • 5.
    5 / 22 Trywith Resources try (FileInputStream in = new FileInputStream("some-file.txt")) { // do something with in } catch(IOException ex) { // log or throw exception }
  • 6.
    6 / 22 Trywith Resources ● Will work everywhere you would expect it ● Use it whenever you need to close something ● Interface AutoClosable as a marker
  • 7.
    7 / 22 Optional ●Can replace working with null values ● Can prevent NullPointerExceptions
  • 8.
    8 / 22 Classicnull check public void classicNull() { String result = methodThatCanReturnNull(); if (result != null) { System.out.println(result); } else { System.out.println("Missing value"); } } private String methodThatCanReturnNull() { if (something) { return "Hello"; }
  • 9.
    9 / 22 Optional publicvoid optional() { Optional<String> result=methodWithOptional(); System.out.println( result.orElse("Missing value")); } private Optional<String> methodWithOptional() { if (something) { return Optional.of("Hello"); } return Optional.empty(); }
  • 10.
    10 / 22 OptionalCommon Methods ● Creating – of, ofNullable, empty ● Checking – isPresent ● Retrieving – get, orElse, map, filter, ...
  • 11.
    11 / 22 Optional ●Can be useful as return value from methods ● Semantic meaning: Value can be absent, needs check ● Null has been called “billion dollar mistake” by its inventor
  • 12.
    12 / 22 Dateand Time API ● Replacement for java.util.Date and Calendar ● Immutable data structures ● Easy manipulation (e.g. date.plusDays(2)) ● Instant: Timestamp ● LocalDate(Time): Date and Time without Timezone ● ZonedDate(Time): Date and Time with Timezones
  • 13.
    13 / 22 Lambdas ●New syntax to pass functionality to methods ● Can be used to replace single method interfaces () -> System.out.println("Hello"); (String name) -> System.out.println(name); Arrays.sort(strArray, (String s1, String s2) -> s2.length() - s1.length());
  • 14.
    14 / 22 Lambdas ●Method references can be used as lambdas – Special syntax using :: String::trim ● New interfaces for common functionality – Function, Predicate, Supplier, Consumer
  • 15.
    15 / 22 Streams ●Functional modification of stream of elements ● map, filter, reduce ● Not related to Java IO-Streams ● Created easily for Collections (List, Set, Map), arrays, File contents, Ranges, ...
  • 16.
    16 / 22 Classicapproach List<String> fullnameOfMinors = new ArrayList<>(); for (Person person: persons) { if (person.age < 18) { fullnameOfMinors.add(person.name); } }
  • 17.
    17 / 22 Streams List<String>fullnameOfMinors = persons.stream() .filter(person -> person.age < 18) .map(person -> person.name) .collect(Collectors.toList());
  • 18.
    18 / 22 Streams ●Intermediate operations – map, filter, distinct, limit, sorted, ... ● Terminal operations – collect, forEach, max, min, ...
  • 19.
    19 / 22 Streams ●Grouping Map<Integer, List<Person>> personsByAge = persons.stream() .collect(groupingBy(Person::getAge));
  • 20.
    20 / 22 Streams ●Sorting by comparator List<Person> personsSortedByAge = persons.stream() .sorted( Comparator.comparing(Person::getAge)) .collect(toList());
  • 21.
    21 / 22 Streams ●Building a String list of elements String stringListOfPersons = persons.stream() .map(person -> person.name) .collect(joining(","));
  • 22.
    22 / 22 Resources ●https://leanpub.com/whatsnewinjava8/read ● https://zeroturnaround.com/rebellabs/java-8-streams-che