Java 8 – Stream
The Java Stream API adds a new abstraction called Stream that lets you process data in a declarative way. The Java Stream API can greatly increase the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code. This style treats the set of elements to be treated as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, and aggregation.
The element flow is processed in the pipeline through an intermediate operation, and finally the result of the previous processing is obtained from the terminal operation
stream of elements +-----> | filter +-> | sorted +-> | map +-> | collect |
What is a Java Stream?
Java Stream is a queue of elements from the data source and supports aggregation operations
Elements are objects of a specific type that form a queue. Streams in Java don’t store elements, they are calculated on demand.
The source of the data source stream. Can be collections, arrays, I/O channels, generators, etc.
Aggregate operations are similar to SQL statements, such as filter, map, reduce, find, match, sorted, etc.
Unlike previous Collection operations, Stream operations have two basic features:
Java Stream Pipe-lining : The intermediate operation returns the stream object itself. Such multiple operations can be cascaded into one pipe, just like a fluent style. This can be optimized for operations such as laziness and short-circuiting.
Java Stream Internal iteration : Previously, collection traversal was done by Iterator or For-Each, and iteratively iterated outside the collection. This is called external iteration. Stream provides an internal iterative approach, implemented through the Visitor pattern (Visitor).
In Java 8, the collection interface has two methods to generate the stream:
Java 8 Stream : Stream () − Creates a serial stream for the collection.
Java 8 Parallel Stream : parallelStream() − Create a parallel stream for the collection.
List < String > stringsList = Arrays.asList ( "ravi" , " " , "kant" , "verma" , "abhi" , " " , "nam" ) ; List < String > filtered = stringsList.stream( ).filter (str -> !String.IsEmpty( ) ).collect ( Collectors . ToList ( ) ) ;
Java Stream Map
The map method is used to map each element to the corresponding result. The following code snippet uses map to output the square of the element:
List < Integer > numbers = Arrays . asList ( 3 , 2 , 2 , 3 , 7 , 3 , 5 ) ; // Get the corresponding square number List < Integer > squaresList = Numbers.Stream( ).Map( I -> I * I ).DISTINCT ( ) . collect ( Collectors . ToList ( ) ) ;
Java stream flatmap
flatMap() is used when we have a stream of collections and we want to flatten it rather than using map() function and getting the nested Stream.
Stream.of(numbers1, numbers2, numbers3) // return Stream<List<Integer>> like Stream[ [1, 2], [3, 4], [5, 6]] .flatMap(list -> list.stream()) // return Stream<Integer> like Stream[1, 2, 3, 4, 5, 6]
Java 8 Stream forEach
Stream provides a new method ‘forEach’ to iterate over every data in the stream. The following code snippet uses forEach to output 10 random numbers:
Random random = new Random ( ) ; random.ints( ).limit ( 10 ).forEach( System.out :: println ) ;
Java 8 Stream Filter
The filter method is used to filter out elements by the set conditions. The following code snippet uses the filter method to filter out an empty string:
List < String > strings = Arrays . asList ( " abc " , " " , " bc " , " efg " , " abcd " , " " , " jkl " ) ; // Get the number of empty strings Int count = strings . stream ( ) . filter ( string -> string . isEmpty ( ) ) . count ( ) ;
Java 8 Stream Limit
The limit method is used to get the specified number of streams. The following code snippet prints 10 pieces of data using the limit method:
Random random = new Random ( ) ; random.ints( ).limit( 10 ).forEach( System.out :: println ) ;
Java 8 Stream Sorted
The sorted method is used to sort the stream. The following code snippet uses the sorted method to sort the 10 random numbers of the output:
Random random = new Random ( ) ; random.ints( ).limit( 10 ).sorted( ).forEach( System.out :: println ) ;
Java Stream Parallel program
parallelStream is an alternative to stream parallel handlers. In the following example we use parallelStream to output the number of empty strings:
List < String > strings = Arrays . asList ( " abc " , " " , " bc " , " efg " , " abcd " , " " , " jkl " ) ; // Get the number of empty strings int COUNT = strings . parallelStream ( ) . filter ( String -> String . isEmpty ( ) ) . COUNT ( ) ;
We can easily run in sequence and switch directly in parallel.
Note: Carefully use parallelStream() because Java 8 Parallel Stream Performance is not good as Compare to Java 8 Stream
Java 8 Stream Collectors
The Collectors class implements many reduction operations, such as converting streams into collections and aggregate elements. Collectors can be used to return a list or 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 ( " Filter list : " + filtered ) ; String mergedString = strings . stream ( ) . filter ( string -> ! string . isEmpty ( ) ) . the collect ( Collectors . joining ( " , " ) ) ; System . out . println ( " Merge string: " + mergedString ) ;
Java 8 Stream statistics
In addition, some collectors that produce statistical results are also very useful. They are mainly used for basic types such as int, double, and long, and they can be used to produce statistical results similar to the following.
List < Integer > Numbers = Arrays, . AsList ( . 3 , 2 , 2 , . 3 , . 7 , . 3 , . 5 ) ; IntSummaryStatistics stats = Numbers . Stream ( ) . MapToInt ( ( X ) -> X ) . SummaryStatistics ( ) ; the System . Out . println ( "The largest number in the list: " + stats . getMax ( ) ) ; System . out . println ( "The smallest number in the list: " + stats . getMin ( ) ) ; System . out . println ( "The sum of all the numbers: " + stats . getSum ( ) ) ; System . out . println ( " Average:" + stats . getAverage ( ) ) ;
With this discussion, i hope you will be able get the feel of what is Stream in Java 8. For Now this is it. Thanks for reading 🙂