In part 2 of an introduction to new features in Java 8, I’ll introduce the new Streams API and new Date/Time API.

Streams

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).

Operations

  • filter : filter results
  • map : transform
  • find : search
  • sort : sort stream output
  • limit : limit number results
  • collect : convert result

Code Samples

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.

	List<Dish> lowCaloricDishes = new ArrayList<>();
	
	for (Dish d: menu) {
		if (d.getCalories() < 400) {
			lowCaloricDishes.add(d);
		}
	}
	Collections.sort(lowCaloricDishes, new Comparator<Dish>(){
		public int compare(Dish d1, Dish d2) {
			return Integer.compare(d1.getCalories(), d2.getCalories());
		}
	});
	List<String> names = new ArrayList<>();
	for (Dish d : lowCaloricDishes){
		names.add(d.getName());
	}
	

Using Stream API, the above can be reduced to the following:

	List<String> names = 
		menu.stream()
		    .filter(d -> d.getCalories() < 400)
		    .sorted(comparing(Dish::getCalories))
		    .map(Dish::getName)
		    .collect(toList));
	

Some of the commonly used stream functions

Function Operation Descriptor
filter Predicate T -> boolean
map Function<T,R> T -> R
sorted Comparator (T,T) -> int
reduce BinaryOperator (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.

	LocalDate date = LocalDate.of(2015,03,18);
	date.getYear(); //2015
	date.getDayOfMonth(); //18
	date.lengthOfMonth();

	LocalTime time = LocalTime.of(13,24,20); //13:24:20
	LocalTIme time2 = LocalTime.parse("13:24:20");

	

Common operations include:

Method Static Description
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