Computer >> Computer tutorials >  >> Programming >> Java

Stream In Java


Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream −

  • Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements.

  • Source − Stream takes Collections, Arrays, or I/O resources as input source.

  • Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.

  • Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.

  • Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.

Example

Let us now see an example −

import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("25", "10", "15", "20", "25");
      Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
      System.out.println("Collection = "+collection);
   }
}

Output

Collection = [100, 130, 150, 20, 200, 50, 80]

Example

Now, let us count the number of elements in the stream using the Java streams counting() method −

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam");
      // count
      long count = stream.collect(Collectors.counting());
      System.out.println("Number of elements in the stream = "+count);
   }
}

Output

Number of elements in the stream = 5