Streams are extremely useful in java 8 programming. A Basic introduction about streams in written in separate blog post. The link is given below.
https://www.blogger.com/blog/post/edit/5251857942821229/8634074333115313571
Stream operations:
Stream
operations are of two categories. One is intermediate operations. Another one
is terminal operations.
Intermediate operations:
These are operations based on filtering, mapping and sorting
data. Some of the functions are listed below.
filter() : Based on a condition, the data is filtered.
map() : Each and every element is transformed using this
function.
flatmap() : It is used for nesting purpose.
distinct() : It gives you the unique value.
sorted() : It sorts
the elements.
Terminal operations:
As a name indicated, this is the last operations in stream.
It may be the end operation or produce the list.
for each() : This is a statement deals with iterative operations.
collect() : It collects thedata
count() : It returns the number of elements.
anymatch() : Checks the element and finds the match.
reduce() : Combines the element and produce the result.
Java program to Filtering and mapping a list of integers
using Streams:
·
As a beginning, create a class “StreamEg”. Save
this file as “StreamEg.java”.
·
Next, create a list of numbers using array.
·
Filter the odd numbers separately.
·
Create the square of the number by doubling
them.
·
Print the output list.
#Java Program
import java.util.Arrays;
import
java.util.List;
import
java.util.stream.Collectors;
//Create a class “StreamEg”
public class
StreamEg {
public static
void main(String[] args) {
//Create a list of integers and assign the values
List<Integer> nos = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18,
19, 20);
//
Filtering odd numbers and square them using stream
List<Integer> oddSquare = nos.stream()
.filter(n -> n % 2 != 0)
.map(n -> n * n)
.collect(Collectors.toList());
//Print the value of list
System.out.println(oddSquare);
}
}
Once you run the program, you will get the output.
These are the ways of using Streams in java. Enjoy Coding!!!!
No comments:
Post a Comment