Revisiting IntStreams in Java8+

Got comments?

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.