Java-8 Streams

Overview:

IMO, Streams are sequence of elements is having various methods pipelined to get the expected results.

Eg.

List <Integer> list= new ArrayList<>(Integer);
for(int i=1;i<11;i++)
list.add(i);
Stream <Integer> listStream=Stream.of(list);//Creation of String from List

Stream doesn't modify the source data.

Operations on Stream:

  • Intermediate Operations--> Lazily executed and returns a stream. It can be pipelined.

  • Terminal Operations--> Produces the result and mark the end of stream.

Examples:

Intermediate Operation:

map()--> It returns the result a stream after applying the functions on the elements of the Stream.

List<Integer> number= Arrays.asList(2,4,6);
List<Integer> addByOne=number.stream().map(m->m+1).collect(Collectors.toList());

filter()--> It returns the Boolean value as per the predicate passed inside the argument.

List<Integer> number= Arrays.asList(2,4,6);
List<Integer> filterFour=number.stream().filter(m->m>4).collect(Collectors.toList());

sorted() -->It returns the sorted value of the original stream without changing the original stream.

List<Integer> number= Arrays.asList(2,4,6);
List<Integer> filterFour=number.stream().sorted().collect(Collectors.toList());