Revisiting IntStreams in Java8+

1 min read

This post is mainly a reiteration of an article, I found online. As of Java 8, we have had the ability to replace looping operations on collections with streams and functional operations. This applies to situations where we don't have an up-front collection to iterate upon.

What traditionally would have been solved by a for-loop:

List<String> list = new ArrayList<>();

for (int i = 0; i < 100; i++) {
    list.add("Username" + i);

// we can now use list

can be replaced by the much more elegant-looking IntStream:

final List<String> list = IntStream.range(0, 100)
	.mapToObj(it -> "Username" + it)

It is a matter of taste, but I prefer the functional approach from the latter example. A nice advantage of using IntStream are the reducing helper methods coming from Stream, such as allMatch, anyMatch, noneMatch, or even reduce itself. This is helpful when testing multiple conditions and need a single answer at the end:

boolean allMatch = final List<String> list = IntStream.range(0, 100)
	.allMatch(it -> booleanTestOn(it))

This is really nothing special that the IntStream class itself brings on the table, but functionality that it inherits from Stream.

Analogous to the IntStream class, alternatives exist for handling Long ( and Double (DoubleStream) values.

Related Articles

Elixir Tip: Case vs. With
3 min read

Elixir Is Not Ruby. Elixir Is Erlang

Try to remember the first time you heard about this fascinating language called Elixir. Chances are, you had by the

2 min read

Write Stupid Code

This is very much a re-interpretation of a post by Thorsten Ball, written back in 2015. Like him, I too

1 min read