Build a stream

Java streams are very powerful to process queries against streams of elements such as sum values in list or filtering elements in a collection. This example will show how to create a stream from values, from an array, file or even create an infinite stream from a function.

Stream from values

By using the static method Stream.of, you can create a sequential ordered stream whose elements are values specified. In example below, we create a stream of strings, trim each element and then join each of them seperated by a comma while returning a string.

@Test
public void stream_from_values() {

    Stream<String> stream = Stream.of("java 8 ", "leveluplunch.com",
            "examples", "exercises");

    String joined = stream.map(String::trim).collect(
            Collectors.joining(","));

    assertEquals("java 8,leveluplunch.com,examples,exercises", joined);
}

Empty stream

@Test
public void empty_stream() {

    Stream<String> emptyStream = Stream.empty();

    long val = emptyStream.count();

    assertTrue(val == 0);
}

Stream from array

You can create a stream from an array by calling the static method Arrays.stream which accepts an array as a parameter. In the example below, we convert an array of ints into an Instream then calling the sum method.

@Test
public void stream_from_array() {

    int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };

    int sum = Arrays.stream(numbers).sum();

    assertEquals(28, sum);
}

Stream from file

Working with files in Java was completely revamped in Java 7 and enhanced in Java 8 to take advantage of the Stream API. The example below shows how to count the number of distinct words in a file by using java.nio.file.Files which contains a useful method Files.line which returns a stream of strings from a specifed file. Breaking it down further, we read the file line by line splitting the words on a space and a period then taking distinct of all of the elements of the single stream produced by the flatMap.

@Test
public void stream_from_file() throws IOException {

    long uniqueWords = java.nio.file.Files
            .lines(Paths.get("word-occurrences-in-file.txt"),
                    Charset.defaultCharset())
            .flatMap(line -> Arrays.stream(line.split(" ."))).distinct()
            .count();

    assertEquals(80, uniqueWords);
}

Stream from function

In the example below, we use Stream.iterate which allows us to call infinite streams, a stream with out a fixed size. In stream filter and slice example, we showed how to limit a stream or truncate it by a specified value which we use below so we don't calculate values forever.

@Test
public void stream_from_function() {

    Stream.iterate(0, n -> n + 3).limit(10).forEach(System.out::println);

}

Output

0
3
6
9
12
15
18
21
24
27

Stream from generate

Similar to the Stream.iterate method above, the Stream.generate allows you to produce an infinite stream of values on demand. The code below will generate a stream of 10 random double numbers from 0 to 1 and we apply the limit otherwise the stream would be unbounded.

@Test
public void stream_from_random() {

    Stream.generate(Math::random).limit(10).forEach(System.out::println);
}

Output

0.0035780282202644287
0.6922214097925711
0.9669092901926246
0.9895696861240524
0.01103751345906101
0.9100674237437933
0.32884490467568905
0.8803886908745164
0.09606236589015216
0.2540385482267097