Java: Endless Stream of Alternating 0s and 1s


This article shows how to create an endless series of zeros and ones using the Java 8 stream API.

The result should look like this:

010101010101010101....

I needed some quick and short way to accomplish this, so it seemed obvious to use the Java 8 stream API for this. After consulting Java’s documentation it turned out that the solution is not only quick and short but also a trivial one-liner:

1
IntStream alternatingStream = IntStream.iterate( 0, i -> i ^ 1 );

Full and executable example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import static java.util.stream.Collectors.joining;

import java.util.stream.IntStream;


public class AlternatingNumbers
{

  public static void main( final String[] args )
  {
    final IntStream alternatingStream = IntStream.iterate( 0, i -> i ^ 1 );

    // Limit is needed here, otherwise this will run
    // into an OutOfMemoryError
    final String result = alternatingStream.limit( 42 )
                                           .mapToObj( Integer::toString )
                                           .collect( joining() );

    System.out.println( result );
  }
}

Result is:

010101010101010101010101010101010101010101