A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.



features of java streams


  • A stream is not a data structure instead it takes input from the Collections, Arrays or I/O
  • Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
  • Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.

Different operations on streams


  • Intermediate operations
  • Terminal operations

Intermediate operations


Following are the intermediate operations

map(): The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.

List number = Arrays.asList(1,2,3,4);
List square = number.stream().map(x->x*x).collect(Collectors.toList());

Check out the complete tutorial on map()

filter(): The filter method is used to select elements as per the Predicate passed as argument

List names = Arrays.asList("HP", "Dell", "Macbook", "Acer", "Lenova");
List result = names.stream().filter(s->s.startsWith("M")).collect(Collectors.toList());

Check out the complete tutorial on filter()

sorted(): The sorted method is used to sort the stream

List names = Arrays.asList("HP", "Dell", "Macbook", "Acer", "Lenova");
List result = names.stream().sorted().collect(Collectors.toList());

Check out the complete tutorial on sorted()

Terminal operations


collect(): The collect method is used to return the result of the intermediate operations performed on the stream.

List number = Arrays.asList(1,2,3,4,5);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());

Checkout the complete tutorial on collect() method here

forEach(): The forEach method is used to iterate through every element of the stream

List number = Arrays.asList(1,2,3,4);
number.stream().map(x->x*x).forEach(System.out::println);

reduce(): The reduce method is used to reduce the elements of a stream to a single value. The reduce method takes a BinarayOperator as a parameter

List number = Arrays.asList(1,2,3,4);
int even = number.stream().filter(x->x%2 == 0).reduce(0,(ans, i)->ans+i);

Check out the complete tutorial on reduce()