4. New Features in Java libraries
Java 8 adds a lot of new classes and extends existing ones in order to provide better support of modern concurrency, functional programming, date/time, and many more.
4.1. Optional
The famous NullPointerException is by far the most popular cause of Java application failures. Long time ago the great Google Guava project introduced the Optionals as a solution to NullPointerExceptions, discouraging codebase pollution with null checks and encouraging developers to write cleaner code. Inspired by Google Guava, the Optional is now a part of Java 8 library.
Optional is just a container: it can hold a value of some type T or just be null. It provides a lot of useful methods so the explicit null checks have no excuse anymore. Please refer to official Java 8 documentation for more details.
We are going to take a look on two small examples of Optional usages: with the nullable value and with the value which does not allow nulls.
- Optional< String > fullName = Optional.ofNullable( null );
- System.out.println( "Full Name is set? " + fullName.isPresent() );
- System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) );
- System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) );
The isPresent() method returns true if this instance of Optional has non-null value and false otherwise. The orElseGet() method provides the fallback mechanism in case Optional has null value by accepting the function to generate the default one. The map() method transforms the current Optional’s value and returns the new Optional instance. The orElse() method is similar to orElseGet() but instead of function it accepts the default value. Here is the output of this program:
- Full Name is set? false
- Full Name: [none]
- Hey Stranger!
Let us briefly look on another example:
- Optional< String > firstName = Optional.of( "Tom" );
- System.out.println( "First Name is set? " + firstName.isPresent() );
- System.out.println( "First Name: " + firstName.orElseGet( () -> "[none]" ) );
- System.out.println( firstName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) );
- System.out.println();
And here is the output:
- First Name is set? true
- First Name: Tom
- Hey Tom!
For more details please refer to official documentation.
4.2. Streams
The newly added Stream API (java.util.stream) introduces real-world functional-style programming into the Java. This is by far the most comprehensive addition to Java library intended to make Java developers significantly more productive by allowing them to write effective, clean, and concise code.
Stream API makes collections processing greatly simplified (but it is not limited to Java collections only as we will see later). Let us take start off with simple class called Task.
- public class Streams {
- private enum Status {
- OPEN, CLOSED
- };
- private static final class Task {
- private final Status status;
- private final Integer points;
- Task( final Status status, final Integer points ) {
- this.status = status;
- this.points = points;
- }
- public Integer getPoints() {
- return points;
- }
- public Status getStatus() {
- return status;
- }
- @Override
- public String toString() {
- return String.format( "[%s, %d]", status, points );
- }
- }
- }
Task has some notion of points (or pseudo-complexity) and can be either OPEN or CLOSED. And then let us introduce a small collection of tasks to play with.
- final Collection< Task > tasks = Arrays.asList(
- new Task( Status.OPEN, 5 ),
- new Task( Status.OPEN, 13 ),
- new Task( Status.CLOSED, 8 )
- );
The first question we are going to address is how many points in total all OPEN tasks have? Up to Java 8, the usual solution for it would be some sort of foreach iteration. But in Java 8 the answers is streams: a sequence of elements supporting sequential and parallel aggregate operations.
- // Calculate total points of all active tasks using sum()
- final long totalPointsOfOpenTasks = tasks
- .stream()
- .filter( task -> task.getStatus() == Status.OPEN )
- .mapToInt( Task::getPoints )
- .sum();
- System.out.println( "Total points: " + totalPointsOfOpenTasks );
And the output on the console looks like that:
- Total points: 18
There are a couple of things going on here. Firstly, the tasks collection is converted to its stream representation. Then, the filter operation on stream filters out all CLOSED tasks. On next step, the mapToInt operation converts the stream of Tasks to the stream of Integers using Task::getPoints method of the each task instance. And lastly, all points are summed up using sum method, producing the final result.
Before moving on to the next examples, there are some notes to keep in mind about streams (more details here). Stream operations are divided into intermediate and terminal operations.
Intermediate operations return a new stream. They are always lazy, executing an intermediate operation such as filter does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate
Terminal operations, such as forEach or sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used. In almost all cases, terminal operations are eager, completing their traversal of the underlying data source.
Yet another value proposition of the streams is out-of-the box support of parallel processing. Let us take a look on this example, which does sums the points of all the tasks.
- // Calculate total points of all tasks
- final double totalPoints = tasks
- .stream()
- .parallel()
- .map( task -> task.getPoints() ) // or map( Task::getPoints )
- .reduce( 0, Integer::sum );
- System.out.println( "Total points (all tasks): " + totalPoints );
It is very similar to the first example except the fact that we try to process all the tasks in parallel and calculate the final result using reduce method.
Here is the console output:
- Total points (all tasks): 26.0
Often, there is a need to performing a grouping of the collection elements by some criteria. Streams can help with that as well as an example below demonstrates.
- // Group tasks by their status
- final Map< Status, List< Task > > map = tasks
- .stream()
- .collect( Collectors.groupingBy( Task::getStatus ) );
- System.out.println( map );
The console output of this example looks like that:
- {CLOSED=[[CLOSED, 8]], OPEN=[[OPEN, 5], [OPEN, 13]]}
To finish up with the tasks example, let us calculate the overall percentage (or weight) of each task across the whole collection, based on its points.
- // Calculate the weight of each tasks (as percent of total points)
- final Collection< String > result = tasks
- .stream() // Stream< String >
- .mapToInt( Task::getPoints ) // IntStream
- .asLongStream() // LongStream
- .mapToDouble( points -> points / totalPoints ) // DoubleStream
- .boxed() // Stream< Double >
- .mapToLong( weigth -> ( long )( weigth * 100 ) ) // LongStream
- .mapToObj( percentage -> percentage + "%" ) // Stream< String>
- .collect( Collectors.toList() ); // List< String >
- System.out.println( result );
The console output is just here:
- [19%, 50%, 30%]
And lastly, as we mentioned before, the Stream API is not only about Java collections. The typical I/O operations like reading the text file line by line is a very good candidate to benefit from stream processing. Here is a small example to confirm that.
- final Path path = new File( filename ).toPath();
- try( Stream< String > lines = Files.lines( path, StandardCharsets.UTF_8 ) ) {
- lines.onClose( () -> System.out.println("Done!") ).forEach( System.out::println );
- }
The onClose method called on the stream returns an equivalent stream with an additional close handler. Close handlers are run when the close() method is called on the stream.
Stream API together with Lambdas and Method References baked by Interface’s Default and Static Methods is the Java 8 response to the modern paradigms in software development. For more details, please refer to official documentation.
4.3. Date/Time API (JSR 310)
Java 8 makes one more take on date and time management by delivering New Date-Time API (JSR 310). Date and time manipulation is being one of the worst pain points for Java developers. The standard java.util.Date followed by java.util.Calendar hasn’t improved the situation at all (arguably, made it even more confusing).
That is how Joda-Time was born: the great alternative date/time API for Java. The Java 8’s New Date-Time API (JSR 310) was heavily influenced by Joda-Time and took the best of it. The new java.time package contains all the classes for date, time, date/time, time zones, instants, duration, and clocks manipulation. In the design of the API the immutability has been taken into account very seriously: no change allowed (the tough lesson learnt from java.util.Calendar). If the modification is required, the new instance of respective class will be returned.
Let us take a look on key classes and examples of their usages. The first class is Clock which provides access to the current instant, date and time using a time-zone. Clock can be used instead of System.currentTimeMillis() and TimeZone.getDefault().
- // Get the system clock as UTC offset
- final Clock clock = Clock.systemUTC();
- System.out.println( clock.instant() );
- System.out.println( clock.millis() );
The sample output on a console:
- 2014-04-12T15:19:29.282Z
- 1397315969360
Other new classes we are going to look at are LocaleDate and LocalTime. LocaleDate holds only the date part without a time-zone in the ISO-8601 calendar system. Respectively, LocaleTime holds only the time part without time-zone in the ISO-8601 calendar system. Both LocaleDate and LocaleTime could be created from Clock.
- // Get the local date and local time
- final LocalDate date = LocalDate.now();
- final LocalDate dateFromClock = LocalDate.now( clock );
- System.out.println( date );
- System.out.println( dateFromClock );
- // Get the local date and local time
- final LocalTime time = LocalTime.now();
- final LocalTime timeFromClock = LocalTime.now( clock );
- System.out.println( time );
- System.out.println( timeFromClock );
The sample output on a console:
- 2014-04-12
- 2014-04-12
- 11:25:54.568
- 15:25:54.568
The LocalDateTime combines together LocaleDate and LocalTime and holds a date with time but without a time-zone in the ISO-8601 calendar system. A quick example is shown below.
- // Get the local date/time
- final LocalDateTime datetime = LocalDateTime.now();
- final LocalDateTime datetimeFromClock = LocalDateTime.now( clock );
- System.out.println( datetime );
- System.out.println( datetimeFromClock );
The sample output on a console:
- 2014-04-12T11:37:52.309
- 2014-04-12T15:37:52.309
If case you need a date/time for particular timezone, the ZonedDateTime is here to help. It holds a date with time and with a time-zone in the ISO-8601 calendar system. Here are a couple of examples for different timezones.
- // Get the zoned date/time
- final ZonedDateTime zonedDatetime = ZonedDateTime.now();
- final ZonedDateTime zonedDatetimeFromClock = ZonedDateTime.now( clock );
- final ZonedDateTime zonedDatetimeFromZone = ZonedDateTime.now( ZoneId.of( "America/Los_Angeles" ) );
- System.out.println( zonedDatetime );
- System.out.println( zonedDatetimeFromClock );
- System.out.println( zonedDatetimeFromZone );
The sample output on a console:
- 2014-04-12T11:47:01.017-04:00[America/New_York]
- 2014-04-12T15:47:01.017Z
- 2014-04-12T08:47:01.017-07:00[America/Los_Angeles]
And finally, let us take a look on Duration class: an amount of time in terms of seconds and nanoseconds. It makes very easy to compute the different between two dates. Let us take a look on that.
- // Get duration between two dates
- final LocalDateTime from = LocalDateTime.of( 2014, Month.APRIL, 16, 0, 0, 0 );
- final LocalDateTime to = LocalDateTime.of( 2015, Month.APRIL, 16, 23, 59, 59 );
- final Duration duration = Duration.between( from, to );
- System.out.println( "Duration in days: " + duration.toDays() );
- System.out.println( "Duration in hours: " + duration.toHours() );
The example above computes the duration (in days and hours) between two dates, 16 April 2014 and 16 April 2015. Here is the sample output on a console:
- Duration in days: 365
- Duration in hours: 8783
The overall impression about Java 8’s new date/time API is very, very positive. Partially, because of the battle-proved foundation it is built upon (Joda-Time), partially because this time it was finally tackled seriously and developer voices have been heard. For more details please refer to official documentation.
4.4. Nashorn JavaScript engine
Java 8 comes with new Nashorn JavaScript engine which allows developing and running certain kinds of JavaScript applications on JVM. Nashorn JavaScript engine is just another implementation of javax.script.ScriptEngine and follows the same set of rules, permitting Java and JavaScript interoperability. Here is a small example.
- ScriptEngineManager manager = new ScriptEngineManager();
- ScriptEngine engine = manager.getEngineByName( "JavaScript" );
- System.out.println( engine.getClass().getName() );
- System.out.println( "Result:" + engine.eval( "function f() { return 1; }; f() + 1;" ) );
The sample output on a console:
- jdk.nashorn.api.scripting.NashornScriptEngine
- Result: 2
We will get back to the Nashorn later in the section dedicated to new Java tools.
4.5. Base64
Finally, the support of Base64 encoding has made its way into Java standard library with Java 8 release. It is very easy to use as following example shows off.
- package com.javacodegeeks.java8.base64;
- import java.nio.charset.StandardCharsets;
- import java.util.Base64;
- public class Base64s {
- public static void main(String[] args) {
- final String text = "Base64 finally in Java 8!";
- final String encoded = Base64
- .getEncoder()
- .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
- System.out.println( encoded );
- final String decoded = new String(
- Base64.getDecoder().decode( encoded ),
- StandardCharsets.UTF_8 );
- System.out.println( decoded );
- }
- }
The console output from program run shows both encoded and decoded text:
- QmFzZTY0IGZpbmFsbHkgaW4gSmF2YSA4IQ==
- Base64 finally in Java 8!
There are also URL-friendly encoder/decoder and MIME-friendly encoder/decoder provided by the Base64 class (Base64.getUrlEncoder() / Base64.getUrlDecoder(), Base64.getMimeEncoder() / Base64.getMimeDecoder()).
4.6. Parallel Arrays
Java 8 release adds a lot of new methods to allow parallel arrays processing. Arguably, the most important one is parallelSort() which may significantly speedup the sorting on multicore machines. The following small example demonstrates this new method family (parallelXxx) in action.
- package com.javacodegeeks.java8.parallel.arrays;
- import java.util.Arrays;
- import java.util.concurrent.ThreadLocalRandom;
- public class ParallelArrays {
- public static void main( String[] args ) {
- long[] arrayOfLong = new long [ 20000 ];
- Arrays.parallelSetAll( arrayOfLong,
- index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
- Arrays.stream( arrayOfLong ).limit( 10 ).forEach(
- i -> System.out.print( i + " " ) );
- System.out.println();
- Arrays.parallelSort( arrayOfLong );
- Arrays.stream( arrayOfLong ).limit( 10 ).forEach(
- i -> System.out.print( i + " " ) );
- System.out.println();
- }
- }
This small code snippet uses method parallelSetAll() to fill up arrays with 20000 random values. After that, the parallelSort() is being applied. The program outputs first 10 elements before and after sorting so to ensure the array is really ordered. The sample program output may look like that (please notice that array elements are randomly generated):
- Unsorted: 591217 891976 443951 424479 766825 351964 242997 642839 119108 552378
- Sorted: 39 220 263 268 325 607 655 678 723 793
4.7. Concurrency
New methods have been added to the java.util.concurrent.ConcurrentHashMap class to support aggregate operations based on the newly added streams facility and lambda expressions. Also, new methods have been added to the java.util.concurrent.ForkJoinPool class to support a common pool (check also our free course on Java concurrency).
The new java.util.concurrent.locks.StampedLock class has been added to provide a capability-based lock with three modes for controlling read/write access (it might be considered as better alternative for infamous java.util.concurrent.locks.ReadWriteLock).
New classes have been added to the java.util.concurrent.atomic package:
- DoubleAccumulator
- DoubleAdder
- LongAccumulator
- LongAdder