Stream in Java

The java.util.Stream interface is a sequence of elements on which you can perform various operations.

Operations on streams are either intermediate or terminal. Terminal operations return a specific type of result, and intermediate operations return the same stream. Thus, you can build chains of several operations on the same stream.

A stream can have as many intermediate operations calls as you want, and the last call to the terminal operation. In this case, all intermediate operations are performed lazily and until the terminal operation is called, no action actually occurs (similar to creating a Thread or Runnable object, without calling start()).

Streams are created based on some sources, for example, classes from java.util.Collection.

Associative arrays (maps) such as HashMap are not supported.

Stream operations can be performed both sequentially and in parallel.

Streams cannot be reused. As soon as any terminal operation has been called, the stream is closed.

In addition to universal object streams, there are special types of streams for working with primitive data types int, long and double: IntStream, LongStream and DoubleStream. These primitive streams work just like regular object streams, but with the following differences:

  • use specialized lambda expressions such as IntFunction or IntPredicate instead of Function and Predicate;
  • support additional final operations sum(), average(), mapToObj().

Ways to create a stream

From the collection:

Stream<String> fromCollection = Arrays.asList("x", "y", "z").stream();

From a set of values:

Stream<String> fromValues = Stream.of("x", "y", "z");

From an array:

Stream<String> fromArray = Arrays.stream(new String[]{"x", "y", "z"});

From the file (each line in the file will be a separate element in the stream):

Stream<String> fromFile = Files.lines(Paths.get("input.txt"));

From the string:

IntStream fromString = "0123456789".chars();

With Stream.builder():

Stream<String> fromBuilder = Stream.builder().add("z").add("y").add("z").build();

With Stream.iterate() (infinite):

Stream<Integer> fromIterate = Stream.iterate(1, n -> n + 1);

With Stream.generate() (infinite):

Stream<String> fromGenerate = Stream.generate(() -> "0");


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed