In this article we will discuss about Stream Filter in Java:
Package : java.util.stream;
Introduced in jdk 1.8 version, java 8 in March 2014
Stream API mainly used to perform some operations in data or Stream Api is used to process the data.
Stream object can be created by two ways :
1) Of()
Example : Stream s1 = Stream.of(2,5,7,9,8);
2) Stream()
List
list.add("chandan");
list.add("baji");
list.add("adhi");
Stream s2 = list.stream();
Stream methods which are performed on Stream and get return “Stream” as output.
1) Filter()
2) Map(), floatmap()
3) Skip(), limit(), distinct()
Other Stream methods are also known as terminal methods and return output for example :
1) count()
2) collect()
For Video :- Click Here
we will provide java 8 Stream filter() example.
We filter a collection for a given Predicate instance. filter() method returns a Stream instance which consists only filtered element on the basis of given Predicate.
As the name says , Stream, means which is flowing continuously like data in list, and we want to filter some result from this list as per your need.
By below example this will get more clear.
Code :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Swap
{
public static void main(String args[])
{
List
list.add("chandan");
list.add("adhiraj");
list.add("Akshat");
list.add("Anant");
List
list.stream().filter( u -> u.startsWith("ch")).forEach(System.out::println );
names.stream().filter( u -> u.endsWith("aj")).forEach(System.out::println );
names.stream().map(u -> u.equals("aviraj")).forEach(System.out::println);
}
}
OutPut:
chandan
aviraj
angraj
devraj
true
false
false
false
Code Explanation : First we create two list with name list & names then we will add some records in the both list.
then simply we will apply , Stream() method on the lists & filter() them as per our need.
finally we will print the required string.
for more deep knowledge :
Click here
Tags :
Java 8 | Stream |
Filter | Stream filter with example |
No comments:
Post a Comment