Java – Stream API

Stream API:

  • Stream is a flow of data.
  • Stream API providing pre-defined functionality by which we can filter the data easily.
  • We always create Streams to Collection objects and filter the data stored in collections.

Note: Stream is a not a data structure hence it will not hold any information. Stream will not change the collection object. It just processes the elements of object by without modifying it.

Creating Stream to List: stream() method returns the stream of any collection object

Stream<Integer> st = list.stream();

forEach() method in Stream interface:

  • Stream API related interfaces and classes belongs to java.util.stream package.
  • forEach() method belongs to Stream class also.
  • We invoke the forEach() method on Stream object to display the data.

Display Stream information using forEach() and Lambda:

import java.util.*;
import java.util.stream.*;
class Main
{
            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50));
                        Stream<Integer> st = list.stream();
                        st.forEach(x->System.out.println(x));
            }
}

Stream and display the list in single line:

import java.util.*;
import java.util.stream.*;
class Main
{
            public static void main(String[] args) {
                        List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50));
                        list.stream().forEach(x->System.out.println(x));
            }
}
Scroll to Top