Java 8 by example - Part 1

2 minute read

This should be helpful for those who already know java and would like to quickly go over what’s Java 8 all about in short with some examples!

For Lambdas you can checkout part 2

Introducing class java.util.StringJoiner

From the Java Doc for the class:

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

API example:

String lang = String.join(" and ", "Java","C","Ruby");

//output below
Java and C and Ruby
//Lets set a default message to show when no value is set
String lang2 = String.join(" and ", "Java","C","Ruby");
lang2.setEmptyValue("No data yet");

No data yet
//Working with existing Collection
Set<String> set = new TreeSet<>();

StringJoiner sj = new StringJoiner(" and ");
set.forEach( s -> sj.add(s));

Apple and Grape and Orange

Next up, we have the Instant class from java.time package.

From the Java Doc for this class:

An instantaneous point on the time-line. This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.

Instant start =;

try {
} catch (InterruptedException e) {
Instant end =;

Duration elapsed = Duration.between(start, end);

Working with Date and time

We have LocalDateTime which is “A date-time without a time-zone”. So it can be used to represent birthdays, an event on a timeline without worrying about the time-zone.

Also there is the new DateTimeFormatter this is a formatter for printing and parsing date-time objects.

DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
LocalDateTime dt =;

//output - yours may differ
//20/11/15 1:52 PM

If you find yourself dealing with date-time of various time-zone then your friend is the new ZonedDateTime. This is a date-time with a time-zone.

ZonedDateTime gmt ="GMT+0"));

//20/11/15 8:22 AM

If we are to find the difference between the two date time given above then use the below:

Duration diff = Duration.between(dt, gmt);


Another example of ZonedDateTime with the help of ZoneId for getting a time-zone based date and time.

ZonedDateTime riyadh ="Asia/Riyadh"));


Now how about printing all Zones (ZoneIds) for Asia using the ZoneId and Lambda approach.

Set<String> availableZoneIds = ZoneId.getAvailableZoneIds(); -> p.contains("Asia")).forEach( i -> System.out.println(i));

We have covered briefly on StringJoiner, Using Lambdas, and Working with Date and Time the Java 8 way.

In the next post I will go over few more Java 8 essentials such as Streams, Default methods and more.

Happy learning!



Leave a Comment