Senior Software Engineer, Craig Handley, talks about interesting tidbits in Java 8.

Interesting tidbits in Java 8

Craig Handley -  09 Dec, 2014

Java 8 has been kicking around for about 8 months now, and we've started to look at transitioning our software from Java 7. Whilst analysing the change, we've eyed a few new features in Java 8 that look really interesting to our engineering teams.

Functional interfaces

Functional interfaces allow default methods to be added to an interface, that do not have to be overridden in the interface implementation. These methods can be run directly from the interface. If the default method is not correct for the implementation, it can be overridden in the implementer.

Lambda

Lambda expressions allow code to be streamlined. When a Lambda expression is used, it is translated into a functional interface at compile time. Here a Lambda expression is used to replace an anonymous inner class with much cleaner and more readable code.

Without Lambda:

aButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println(“Action has been performed”);
}
});

With Lambda:

aButton.addActionListener(e -> {
System.out.println(“Action has been performed”);
});

And another example

Without Lambda:

Runnable aRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Running without Lambda");
}
};

With Lambda:

Runnable aRunnable = () -> { System.out.println("Running with Lambda"); };

Java time

Java 8 has introduced a completely new date / time API. The new API brings ease-of-use and accuracy long provided by the popular Joda time API into the core Java library. It has classes LocalDate, LocalTime and LocalDateTime which can be used in much the same way as the Joda equivalents.Java time

All of the core classes are constructed via factory methods:

LocalDateTime timePoint = LocalDateTime.now(); // The current date and time
LocalDate.of(2012, Month.DECEMBER, 12); // from values
LocalTime.of(17, 18); // the train I took home today
LocalTime.parse("10:15:30"); // From a String

The Period class represents a value such as “2 months and 1 day,” which is a distance on the timeline:

Period period = Period.of(3, 2, 1); // 3 years, 2 months, 1 day
// You can modify the values of dates using periods
LocalDate newDate = oldDate.plus(period);
LocalDateTime newDateTime = oldDateTime.minus(period);

A Duration is a distance on the timeline measured in terms of time, and it fulfills a similar purpose to Period, but with different precision:

// A duration of 3 seconds and 5 nanoseconds
Duration duration = Duration.ofSeconds(3, 5);
Duration oneDay = Duration.between(today, yesterday);

Streams

A new collection has been introduced by Java 8 called ‘stream’, they are not meant to replace any of the other collection objects, they are to be used to make manipulating data easier and faster. A stream is a one-time-use Object. Once it has been traversed, it cannot be traversed again. A stream can be used in two modes sequential and parallel (where multicore processors are available).

You obtain a stream from a collection like this:

List<String> items = new ArrayList<String>();
items.add("one");
items.add("two");
items.add("three");
Stream<String> stream = items.stream();

Filtering streams:

List<String> filtered = stream().filter( item -> item.startsWith("o") ).collect(Collectors.toList());

This code will filter the stream, so as to only include items that start with with “o” and collect them into a new List.

Mapping streams:

List<String> mapped = items.stream().map( item -> item.toUpperCase() ).collect(Collectors.toList());

This code will map the contents of the stream to uppercase versions of themselves, and collect them into a new List.

Retrieving min and max values:

String shortest = items.stream().min(Comparator.comparing(item -> item.length())).get();

This will retrieve the shortest value from the stream and return it.

Counting items within a stream:

long count = items.stream().filter( item -> item.startsWith("t") ).count();

Will return the count of items within the stream that match the filter (starts with “t”)

Parallel sorting

There is now a concise way to speed up the sorting of collections. It automatically breaks up the target array into multiple parts that can be processed across a number of cores before being grouped back together. Instead of:

Arrays.sort(anArray);

You can now use the following:

Arrays.parallelSort(anArray);

The one issue that may occur however in highly multi-threaded environment, is that the benefits of this approach will begin to diminish due to the cost of increased CPU context switches.

Subscribe to this blog

Use of this website and/or subscribing to this blog constitutes acceptance of the travel.cloud Privacy Policy.

Comments