Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Holiday Calendar 2016 (Day 21): Concatenate Java Streams

DZone's Guide to

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.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.


Image title


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 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.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java ,tutorial ,java streams ,concatenation

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}