Java 8 introduces a new abstraction called Stream that lets you process data in a declarative way. In Java 8, you can refactor the preceding code using streams, like so:
List
In addition, you can explicitly execute a stream in parallel by using the method parallelStream instead of stream from a collection source. (Don’t worry about the details of this code for now. You’ll learn much more about the Streams API in Chapter 3.)
Enhanced Interfaces
Interfaces in Java 8 can now declare methods with implementation code thanks to two improvements. First, Java 8 introduces
Default methods can also serve as a multiple inheritance mechanism for behavior. In fact, prior to Java 8, a class could already implement multiple interfaces. Now, you can inherit default methods from multiple different interfaces. Note that Java 8 has explicit rules to prevent inheritance issues common in C++ (such as the diamond problem).
Second, interfaces can now also have
New Date and Time API
Java 8 introduces a brand new Date and Time API that fixes many problems typical of the old Date and Calendar classes. The new Date and Time API was designed around two main principles: Domain-driven design
The new Date and Time API precisely models various notions of date and time by introducing new classes to represent them. For example, you can use the class Period to represent a value like “2 months and 3 days” and ZonedDateTime to represent a date–time with a time zone. Each class provides domain-specific methods that adopt a fluent style. Consequently, you can chain methods to write more readable code. For example, the following code shows how to create a new LocalDateTime object and add 2 hours and 30 minutes: LocatedDateTime coffeeBreak = LocalDateTime.now() .plusHours(2) .plusMinutes(30); Immutability
One of the problems with Date and Calendar is that they weren’t thread-safe. In addition, developers using dates as part of their API can accidentally update values unexpectedly. To prevent these potential bugs, the classes in the new Date and Time API are all immutable. In other words, you can’t change an object’s state in the new Date and Time API. Instead, you use a method to return a new object with an updated value.
The following code exemplifies various methods available in the new Date and Time API:
ZoneId london = ZoneId.of("Europe/London");
LocalDate july4 = LocalDate.of(2014, Month.JULY, 4);
LocalTime early = LocalTime.parse("08:45");
ZonedDateTime flightDeparture = ZonedDateTime.of(july4, early, london);
System.out.println(flightDeparture);
LocalTime from = LocalTime.from(flightDeparture);
System.out.println(from);
ZonedDateTime touchDown
= ZonedDateTime.of(july4,
LocalTime.of (11, 35),
ZoneId.of("Europe/Stockholm"));
Duration flightLength = Duration.between(flightDeparture, touchDown);
System.out.println(flightLength);
This code will produce an output similar to this: 2015-07-04T08:45+01:00[Europe/London] 08:45 PT1H50M PT269H46M55.736S
CompletableFuture