Java Holiday Calendar 2016 (Day 21): Concatenate Java Streams
Merging your streams through concatenation can allow one stream to lazily consume others, saving you time and making your code more efficient.
Join the DZone community and get the full member experience.
Join For FreeToday'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 streaming from the list or using the Stream.builder() will not do.
As an example, we have three streams with words that are relevant to US history and its Constitution:
// From 1787
final Stream preamble = Stream.of(
"We", "the", "people", "of", "the", "United", "States"
);
// From 1789
final Stream firstAmendment = Stream.of(
"Congress", "shall", "make", "no", "law",
"respecting", "an", "establishment", "of", "religion"
);
// From more recent days
final Stream 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
Stream.concat(
preamble,
Stream.concat(firstAmendment, epilogue)
)
.forEach(System.out::println);
// Works for any number of streams
Stream.of(preamble, firstAmendment, epilogue)
.flatMap(Function.identity())
.forEach(System.out::println);
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:
We
the
people
of
the
United
States
Congress
shall
make
no
law
respecting
an
establishment
of
religion
In
reason
we
trust
Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.
Opinions expressed by DZone contributors are their own.
Comments