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 single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies


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.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:
java ,tutorial ,java streams ,concatenation

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}