Background: multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone.

Solutions: Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it.

What is Stream Link to heading

  • A stream provides a set of elements in a sequential manner. It never stores the elements.
  • Stream takes Collections, Arrays or I/O as input.
  • Aggregate operations like filter, map, limit, reduce, find, mathch and so on.
  • can be pipelined. Most of the stream operations return stream itself. These operations are called intermediate operations and their function is to take input, process them and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.
  • Stream operations do the iterations internally over the source elements provided.

stream() Link to heading

  • stream() returns sequential stream considering collection as its source.
  • parallelStream().

forEach() Link to heading

iterate each element of stream.

map() Link to heading

map method is used to map each element to its corresponding result. People usually write lambda expression inside map().

List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter() Link to heading

filter method is used to eliminate elements based on a criteria.

//get count of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();

sorted() Link to heading

the sorted method is used to sort the stream.

Random random = new Random();
//below two are equal.
//random.ints().limit(10).sorted().forEach(System.out::println);
random.ints().limit(10).sorted().forEach(x->System.out.println(x));

collect() Link to heading

Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string.

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

System.out.println("Filtered List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged String: " + mergedString);