Stream intermediate operations

Representation of Stream as a cascade

There are a few operations that processes a stream and output stream as source for terminal operations. Above, we can see some of these methods, yours descriptions and examples. Just short, just directly.

Filtering and Mapping


  • Returns a stream with no duplicate elements.

filter(Predicate p)

  • Returns a stream with only those elements that return true for the Predicate.

map(Function f)

  • Returns a stream where the given Function is applied to each element on the input stream.

mapToInt(), mapToDouble(), mapToLong()

  • Like map(), but producing streams of primitives rather than objects

Maps and FlatMaps

  • Take a single value as input and generates a single value of output stream. 1-to-1 mapping.
  • Streams of stream. Take the input stream, generates a stream for each element and join the result.


List<String> output = reader.lines().flatMap(line -> Stream.of(line.split(REGEXP))).filger(word -> word.length() > 0).collect(Collectors.toList());

Restricting the size of a stream

skip(long n)

limit(long n)

Ex.: String output = bufferedReader.lines().skip(2).limit(2).collect(Collectors.joining());

Sorting and unsorting

sorted(Comparator c)

  • sorted(): based on natural order.


  • can improve efficiency of operations like distinct() and groupingby()

Observing Stream Elements


  • Not modify the elements of the stream. Each of element is passed by the accpet() metodh of the Consumer.

Leave a Reply

Your email address will not be published. Required fields are marked *