Example of different kind of streams in Java 8 [Part 2]

In the previous post we have alreday seen different ways of creating a Stream. In this post we will check some other Stream operations.

Empty Stream

The empty() method should be used in case of a creation of an empty stream:

Stream emptyStream = Stream.empty();

Its often the case that the empty() method is used upon creation to avoid returning null for streams with no element:

public Stream streamOf(List list) {
    return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}

Stream of Array and Collection

Array/ Collection can also be a source of a Stream:

// Array source of Stream
Stream streamOfArray = Stream.of("a", "b", "c");

// Collection source of Stream
Collection collection = Arrays.asList("a", "b", "c");
Stream streamOfCollection = collection.stream();

Stream.builder()

When builder is used the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream:

Stream streamBuilder =
  Stream.builder().add("a").add("b").add("c").build();

Using Stream.generate() or Stream.iterate() functions

 Stream stream = Stream.generate(() -> { return new Date();});
 stream.forEach(p -> System.out.println(p));

The generate() method accepts a Supplier for element generation. As the resulting stream is infinite, developer should specify the desired size or the generate() method will work until it reaches the memory limit:

Stream streamGenerated =
  Stream.generate(() -> "element").limit(10);

Another way of creating an infinite stream is by using the iterate() method:

Stream streamIterated = Stream.iterate(40, n -> n + 2).limit(20);

The first element of the resulting stream is a first parameter of the iterate() method. For creating every following element the specified function is applied to the previous element. In the example above the second element will be 42.

Java-8 12 Stream 12

FOLLOW US ON LinkedIn



Explore Tutu'rself