Major New Language Features Neil Brown 10/2014 @neiljbrown neiljbrown.com
Jun 14, 2015
Overview of Major New Features
● Lambda expressions● Streams (aka bulk / aggregate data ops)● Default methods● Date/time API● Optional type
Lambda Expressions
Anonymous function, with no classExpression syntax like that of a method(String s1, String s2) -> s1.length() - s2.length();
Assign to variables or pass as method paramBenefits
● Another means of code reuse● Terser implementation of single abstract methods (SAMs)
Streams API
APIs support aggregating ‘streams’ on-the-fly, concurrently, using functional methods eg filter‘Stream’ - seq. of elements from a source supporting aggregating (‘bulk’) data operationsConcept:
● Convert source to stream● Process elements in parallel, concurrently● Collect resulting elements
Streams API
Sources include Collections, Array, I/O classesBenefits● Better performance via lazy evaluation of
methods on stream and parallel processing● Replace boilerplate external iteration code eg
List<Student> students = new ArrayList<>(100); ...List<Student> filteredStudents = students.stream()
.filter(s -> s.getDob().getYear() > yearOfBirthFilter)
.collect(Collectors.toList());
Default Methods
Interfaces can include default implementationsinterface Logger {
default void info(String message) {
Logger.log("[INFO]", message);
} ...}
Compiler uses the ‘default method’ in classes which don’t provide own implementation
Default Methods
Interfaces still not permitted to have stateBenefit
● Java APIs can evolve without breaking backwards compatibility eg add functional methods to Collection interfaces for Streams
Date & Time API
java.time.* - Addresses issues with java.util.Date and Calendar
● Thread-safe. Immutable classes.● Consistent design, inspired by Joda-Time● Better time-zone support
Fluent API; Major classes:● LocalDateTime and ZonedDateTime - Factory
methods, parsing, truncation● Period and Duration - lengths of time
java.util.Optional
New type for value that may be nullUsed as method return type rather than null eg Optional<Soundcard> optionalSoundcard = computer.getSoundcard();
Forces client to deal with null at compile-timeProvides convenience methods ifPresent(), orElse() for simpler handling of possible nullProvides null-safe functional methods filter(), map() etc
java.util.Optional
Benefits● More expressive / explicit API methods● Reduces no. of NullPointerException ● Provided null safe methods reduce need for nested
conditional statements to handle null refs
Code Examples
Code examples for each new feature● https://bitbucket.org/neilbrown - ‘java8-
examples’ repository
Includes pre Java 8 equivalent code to help identify eligible cases