Posts

Showing posts with the label Stream

Java 8 Stream API

  Introduced in   Java 8   along with other programming features,   Stream API   provides various functionalities to process a collection of objects. Before we dive into Streams API, let’s see for an example, how we used to iterate a List and calculate the sum before the introduction of Streams in Java 8. List<Integer> numList = Arrays.asList(2,5,7,9,10,20,30,40); int sum = 0; Iterator<Integer> iterator = numList.iterator(); while (iterator.hasNext()) { int number = iterator.next(); if (number< 10) { sum += number; } } The above codes works perfectly fine and the variable sum will have the value 23 as the sum of numbers less than 10, but there are few issues with this code. The code has to be written on how the list should be iterated although the requirement is just to obtain the sum of the numbers which are less than 10 The program is sequential A lot of code must be written to perform this simple calculation. To avoid the above issues, Stream API was i