Tag Archives: java8

04 Apr

Sequence Streams for Java 8

Since Java 8 was introduced last week, I started playing around with the new features it provides, e.g. lambda expressions, streams, …

After taking a closer look at the streaming API, I noticed that there was no out-of-the-box support for generating number sequences. Thus, I created this little project on GitHub: https://github.com/jakobk/sequence-streams.

Using the class Sequence, you can improve classic for-loops by making use of the new streaming API of Java 8. Consider the following example:

List<Person> persons = new ArrayList<Person>(100);
for (int i = 0; i < 100; i++) {
    persons.add(new Person(i));
// use persons ...

The same can be accomplished using Sequence in combination with the new streaming API:

List<Person> persons = Sequence.stream(0, 100)
// use persons ...

The class Sequence provides various methods for generating all kinds of integer sequence streams, e.g. sequential or parallel streams, using different step sizes, counting up or counting down, etc.

After some further research, I found out that Tomasz Nurkiewicz created something similar to my Sequence class, however, much more powerful. His project LazySeq is also hosted on GitHub: https://github.com/nurkiewicz/LazySeq. Using LazySeq you can easily create various number sequences, including infinite ones. This is very similar to what already exists in clojure: lazy-seq.