SlideShare a Scribd company logo
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

More Related Content

ODP
Ceph Day NYC: Developing With Librados
PDF
Kotlin workshop 2018-06-11
ODP
jTransfo lightning talk
ODP
JavaScript global object, execution contexts & closures
PDF
JavaScript Execution Context
PDF
Containers and Logging
PDF
Lambdas HOL
PDF
Scala Code Analysis at Codacy
Ceph Day NYC: Developing With Librados
Kotlin workshop 2018-06-11
jTransfo lightning talk
JavaScript global object, execution contexts & closures
JavaScript Execution Context
Containers and Logging
Lambdas HOL
Scala Code Analysis at Codacy

What's hot (20)

PPTX
Logs management
PDF
Fluent Bit: Log Forwarding at Scale
PPTX
PPTX
An introduction to Object Oriented JavaScript
PPTX
Welcome to rx java2
PDF
Memory management
PDF
Kotlin functional programming basic@Kotlin TW study group
PPTX
Reactive Extensions for JavaScript
ODP
JavaScript Object Oriented Programming Cheat Sheet
PDF
Streams or Loops? Java 8 Stream API by Niki Petkov - Proxiad Bulgaria
PDF
DConf 2016: Keynote by Walter Bright
PDF
Cap'n Proto (C++ Developer Meetup Iasi)
PDF
Ceph Day Chicago: Using Ceph for Large Hadron Collider Data
PDF
Fluent-bit
PDF
Clojure - LISP on the JVM
PDF
Big Data for Mobile
PDF
Local state management with Apollo | Виталий Паршиков | Zlit Tech
PPTX
Scalable Applications with Scala
PDF
Handout: 'Open Source Tools & Resources'
Logs management
Fluent Bit: Log Forwarding at Scale
An introduction to Object Oriented JavaScript
Welcome to rx java2
Memory management
Kotlin functional programming basic@Kotlin TW study group
Reactive Extensions for JavaScript
JavaScript Object Oriented Programming Cheat Sheet
Streams or Loops? Java 8 Stream API by Niki Petkov - Proxiad Bulgaria
DConf 2016: Keynote by Walter Bright
Cap'n Proto (C++ Developer Meetup Iasi)
Ceph Day Chicago: Using Ceph for Large Hadron Collider Data
Fluent-bit
Clojure - LISP on the JVM
Big Data for Mobile
Local state management with Apollo | Виталий Паршиков | Zlit Tech
Scalable Applications with Scala
Handout: 'Open Source Tools & Resources'
Ad

Similar to Modern Java Features (20)

PPTX
New features in jdk8 iti
PDF
Java SE 8 library design
PDF
Dragoncraft Architectural Overview
PPTX
Apache pig presentation_siddharth_mathur
PDF
Test strategies for data processing pipelines
PDF
Data pipelines from zero to solid
PDF
Test strategies for data processing pipelines, v2.0
PPTX
Apache pig presentation_siddharth_mathur
PDF
Fluentd vs. Logstash for OpenStack Log Management
PDF
Java 8
PDF
PDF
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
PPTX
New Features in JDK 8
PDF
Custom Pregel Algorithms in ArangoDB
PDF
Apache airflow
PDF
2014 10 java 8 major new language features
ODP
Lambda Chops - Recipes for Simpler, More Expressive Code
ODP
Hello Java 8
PDF
Java Concurrency in Practice
PPTX
Airflow 101
New features in jdk8 iti
Java SE 8 library design
Dragoncraft Architectural Overview
Apache pig presentation_siddharth_mathur
Test strategies for data processing pipelines
Data pipelines from zero to solid
Test strategies for data processing pipelines, v2.0
Apache pig presentation_siddharth_mathur
Fluentd vs. Logstash for OpenStack Log Management
Java 8
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
New Features in JDK 8
Custom Pregel Algorithms in ArangoDB
Apache airflow
2014 10 java 8 major new language features
Lambda Chops - Recipes for Simpler, More Expressive Code
Hello Java 8
Java Concurrency in Practice
Airflow 101
Ad

More from Florian Hopf (14)

PDF
Einführung in Elasticsearch
PDF
Introduction to elasticsearch
PDF
Java clients for elasticsearch
PDF
Einfuehrung in Elasticsearch
PDF
Data modeling for Elasticsearch
PDF
Einführung in Elasticsearch
PDF
Elasticsearch und die Java-Welt
PDF
Anwendungsfälle für Elasticsearch JAX 2015
PDF
Anwendungsfälle für Elasticsearch JavaLand 2015
PDF
Anwendungsfaelle für Elasticsearch
PDF
Search Evolution - Von Lucene zu Solr und ElasticSearch (Majug 20.06.2013)
PDF
Search Evolution - Von Lucene zu Solr und ElasticSearch
PDF
Akka Presentation Schule@synyx
PDF
Lucene Solr talk at Java User Group Karlsruhe
Einführung in Elasticsearch
Introduction to elasticsearch
Java clients for elasticsearch
Einfuehrung in Elasticsearch
Data modeling for Elasticsearch
Einführung in Elasticsearch
Elasticsearch und die Java-Welt
Anwendungsfälle für Elasticsearch JAX 2015
Anwendungsfälle für Elasticsearch JavaLand 2015
Anwendungsfaelle für Elasticsearch
Search Evolution - Von Lucene zu Solr und ElasticSearch (Majug 20.06.2013)
Search Evolution - Von Lucene zu Solr und ElasticSearch
Akka Presentation Schule@synyx
Lucene Solr talk at Java User Group Karlsruhe

Recently uploaded (20)

PDF
System and Network Administraation Chapter 3
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PDF
top salesforce developer skills in 2025.pdf
PPTX
Transform Your Business with a Software ERP System
PDF
Cost to Outsource Software Development in 2025
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
System and Network Administraation Chapter 3
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Navsoft: AI-Powered Business Solutions & Custom Software Development
iTop VPN Free 5.6.0.5262 Crack latest version 2025
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Why Generative AI is the Future of Content, Code & Creativity?
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
top salesforce developer skills in 2025.pdf
Transform Your Business with a Software ERP System
Cost to Outsource Software Development in 2025
Reimagine Home Health with the Power of Agentic AI​
Computer Software and OS of computer science of grade 11.pptx
How to Choose the Right IT Partner for Your Business in Malaysia
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Odoo POS Development Services by CandidRoot Solutions
Embracing Complexity in Serverless! GOTO Serverless Bengaluru

Modern Java Features

  • 1. 1 / 22 Modern Java 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 Try with Resources ● Aka Automatic resource management ● Helps with forgetting closing resources – Files – IO Streams – Database connections – ...
  • 4. 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. 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. 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. 7 / 22 Optional ● Can replace working with null values ● Can prevent NullPointerExceptions
  • 8. 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. 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. 10 / 22 Optional Common 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 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. 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 Classic approach 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