top of page

Stream API of Java

1. Stream API


  • Introduced in Java 8.

  • Provides a functional approach to processing collections of objects.


2. Features of Java Stream


  • It does not store element. It only conveys elements from a source through a pipeline of computational operations.

  • It is lazy and evaluates code only when required.

  • It has three main parts, Source, Intermediate Operation and Terminal Operation


Where :

  • Source can be a data structure, an array, etc.

  • Intermediate Operation can be a pipelined operations which is lazily executed and returns a stream as a result.

  • Terminal Operation can be an operation which starts the internal pipeline operations and returns a non-stream as a result.

3. List of Intermediate Operations


  1. filter

  2. map

  3. flatmap

  4. sorted

  5. peek

  6. distinct

  7. limit

  8. skip


Example:


map : It is used to map the items in the collection to other objects according to the function passed as argument.


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

filter : It is used to select element as per the Predicate passed as argument.


List names = Arrays.asList("Terminal Operation","Immediate Operation","Source");
List result = names.stream().filter(n->n.startsWith("S")).collect(Collectors.toList());

sorted : It is used to sort the Stream


List names = Arrays.asList("Terminal Operation","Immediate Operation","Source");
List result = names.stream().sorted().collect(Collectors.toList());

4. List of Terminal Operations


  1. forEach

  2. forEachOrdered

  3. toArray

  4. reduce

  5. collect

  6. min

  7. max

  8. count

  9. anyMatch

  10. allMatch

  11. noneMatch

  12. findFirst

  13. findAny


Example :


collect : It 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(n->n*n).collect(Collectors.toSet());

forEach : It is used to iterate through every element of the stream.


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

count : It is used to count the number of elements of the stream.


List number = Arrays.asList(1,2,3,4,5);
long count = number.stream().count();

Ref :


http://tutorials.jenkov.com/java-functional-programming/streams.html

https://www.javatpoint.com/java-8-stream

https://www.geeksforgeeks.org/stream-in-java/


Single post: Blog_Single_Post_Widget
bottom of page