Day 21, Java Holiday Calendar 2016, Concatenate Java Streams
Today's tip is about concatenating streams. The task of the day is to construct a concatenated stream that lazily consumes a number of underlying streams. So, dumping the content from the various streams into a List and then stream from the list or using the Stream.builder() will not do.
As an example, we have three streams with words that are relevant to the US history and constitution:
// From 1787
preamble = Stream.of(
"We", "the", "people", "of", "the", "United", "States"
// From 1789
firstAmendment = Stream.of(
"Congress", "shall", "make", "no", "law",
"respecting", "an", "establishment", "of", "religion"
// From more recent days
epilogue = Stream.of(
"In", "reason", "we", "trust"
Creating a concatenated stream can be done in many ways including these:
// Works for a small number of streams
// Works for any number of streams
Stream.of(preamble, firstAmendment, epilogue)
Both methods will produce the same result and they will also close the underlying streams upon completion. Personally, I prefer the latter method since it is more general and can concatenate any number of streams. This is the output of the program: