In part 2 of an introduction to new features in Java 8, I’ll introduce the new Streams API and new Date/Time API.
The Streams API is a new API in Java 8 to improve processing over sequences or collections of data. Streams have 3 parts (datasource, operations, terminal operation).
- filter : filter results
- map : transform
- find : search
- sort : sort stream output
- limit : limit number results
- collect : convert result
Operations return the stream as a result, allowing operations to be pipelined together. This results in much cleaner and less code. Here is an example of code that gathers a list of dishes under 400 calories and stores the name of a dish in a list.
Using Stream API, the above can be reduced to the following:
Some of the commonly used stream functions
|filter||Predicate||T -> boolean|
|map||Function<T,R>||T -> R|
||(T,T) -> int|
||(T,T) -> T|
LocalDate and LocalTime
In Java 8, there is a new API for working with Dates, which more resembles the popular Joda Time library. There are two main classes, LocalDate and LocalTime. Both of these classes are immutable unlike the existing Date and Calendar classes. This means once the instance is created, you cannot make a change to the date. Any setter methods provider will actually return a new object instead of modifying the existing one, which will not lead to unexpected results.
The classes are pretty simple to work with, below shows some sample code.
Common operations include:
|between||Yes||Create interval between two points in time|
|parse||Yes||create instance from String|
|addTo||No||create copy and add interval to it|
|isNegative||No||check if interval is negative|
|minus||No||create copy and substract interval from it|