Java 8 java.time.temporal. TemporalAdjusters and Stream.flatMap() Tutorial

Last updated
App Shah

Crunchify » Java and J2EE Tutorials » Java 8 java.time.temporal. TemporalAdjusters and Stream.flatMap() Tutorial

Java 8 java.time.temporal.TemporalAdjusters and Stream.flatMap() Tutorial

It’s been almost 2 years Java 8 was released, March 2014. I’m sure most of the companies still using Java 7 with Apache Tomcat in their production environment but recently it’s picking up some momentum.

As most the companies still using Java 7 there are quite a few features unnoticed by the world.

Sometime back we have written a detailed article on Java 8 Stream API and Lambda Expression. In this tutorial we will go over java.time.temporal.TemporalAdjusters and flatMap() example.

TemporalObjects

What are tempoalObjects in Java? It’s framework level interface dealing with date and time object, mainly read-only objects which provides access in generic manner.

TemporalAdjusters

TemporalAdjusters are a key tool for modifying temporal objects. There are two ways you could use TemporalAdjuster.

  1. Invoke the method on the interface directly
  2. use Temporal.with(TemporalAdjuster)
public interface TemporalAdjuster Example - Crunchify

Stream.flatMap()

Java map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. What is a difference?

  • map operation produces one output value for each input value
  • flatMap operation produces an arbitrary number (zero or more) values for each input value

Let’s get started on Tutorial

  • Create class CrunchifyJava8TemporalAdjustersAndFlatMap.java
  • We will create two simple methods
    • crunchifyStreamFlatMapExample
    • crunchifyTemporalExample
  • All details are provided in each method itself as comment
  • Run the program and checkout result
  • make sure you have setup JDK 8 in Eclipse environment

CrunchifyJava8TemporalAdjustersAndFlatMap.java

package crunchify.com.tutorials;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author crunchify.com
 * Java 8 java.time.temporal. TemporalAdjusters and Stream.flatMap() Tutorial
 */

public class CrunchifyJava8TemporalAdjustersAndFlatMap {
	public static void main(String[] args) {
		
		// Stream.flatMap() example
		crunchifyStreamFlatMapExample();
		
		// TemporalAdjuster example
		crunchifyTemporalExample();
	}
	
	public static void crunchifyStreamFlatMapExample() {
		List<CrunchifyCompany> companyList = new ArrayList<>();
		
		CrunchifyCompany gName = new CrunchifyCompany("Google");
		gName.add("Gmail");
		gName.add("Docs");
		gName.add("Google Apps");
		
		CrunchifyCompany yName = new CrunchifyCompany("Yahoo");
		yName.add("YMail");
		yName.add("Yahoo Sites");
		
		companyList.add(gName);
		companyList.add(yName);
		
		// Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped
		// stream produced by applying the provided mapping function to each element
		crunchifyLog("Here is a list of all Company product list:");
		List<String> crunchifyList = companyList.stream()
				.flatMap(element -> element.getProducts().stream()).collect(Collectors.toList());
		
		crunchifyLog(crunchifyList.toString());
		
	}
	
	private static void crunchifyLog(String msg) {
		System.out.println(msg);
		
	} 
	
	static class CrunchifyCompany {
		private String companyName;
		private final Set<String> products;
		
		public CrunchifyCompany(String companyName) {
			this.setCompanyName(companyName);
			this.products = new HashSet<>();
		}
		
		public void add(String animal) {
			
			// add(): Adds the specified element to this set if it is not already present (optional operation).
			// More formally, adds the specified element e to this set if the set contains no element e2 such that Objects.equals(e, e2).
			// If this set already contains the element, the call leaves the set unchanged and returns false.
			this.products.add(animal);
		}
		
		public Set<String> getProducts() {
			
			return products;
		}
		
		public String getCompanyName() {
			
			return companyName;
		}
		
		public void setCompanyName(String companyName) {
			this.companyName = companyName;
		}
		
	}
	
	public static void crunchifyTemporalExample() {
		
		// A date-time without a time-zone in the ISO-8601 calendar system
		// String time = LocalDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
		
		// Let's return currentitme - 1 year
		LocalDateTime crunchifyTime = LocalDateTime.now().minusYears(1);
		
		// TemporalAdjusters: Adjusters are a key tool for modifying temporal objects
		crunchifyLog("\n- get 1st Day of Month: " + crunchifyTime.with(TemporalAdjusters.firstDayOfMonth()));
		
		// Returns the "last day of month" adjuster
		crunchifyLog("- get Last Day of Month: " + crunchifyTime.with(TemporalAdjusters.lastDayOfMonth()));
		
		// Returns the "first day of year" adjuster
		crunchifyLog("- get 1st Day of Year: " + crunchifyTime.with(TemporalAdjusters.firstDayOfYear()));
		
		// Returns the next day-of-week adjuster
		crunchifyLog("- get next Day Of Week: "
				+ crunchifyTime.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY)));
		
		// Returns the "last day of year" adjuster
		crunchifyLog("- get last Day of Year: " + crunchifyTime.with(TemporalAdjusters.lastDayOfYear()));
		
		// Returns the last in month adjuster
		crunchifyLog("- get last Day Of Week: "
				+ crunchifyTime.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)));
	}
}

Output:

Here is a console result. Just run above Java program and you will see result like below.

Here is a list of all Company product list:
[Gmail, Docs, Google Apps, YMail, Yahoo Sites]

- get 1st Day of Month: 2015-01-01T12:07:11.980
- get Last Day of Month: 2015-01-31T12:07:11.980
- get 1st Day of Year: 2015-01-01T12:07:11.980
- get next Day Of Week: 2015-01-14T12:07:11.980
- get last Day of Year: 2015-12-31T12:07:11.980
- get last Day Of Week: 2015-01-30T12:07:11.980

Let us know if you face any issue running above program.

Leave a Comment