In this tutorial, we will see “How to use Streams to Filter a List in Java 8?”. We are going to use how Java 8 Streams API can be used to filter an ArrayList. Java 8 streams filter example
Check out: ArrayList ListIterator in Java with Examples
Java 8 Streams Filter Example...!!! Share on X
Filter List using ‘Java 8 Streams’
/**
* Filter a List using Java8 Streams
* @author Deepak Verma
*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Filter_List_Using_Java8_Streams {
public static void main(String[] args) {
List<Actor> listOfActors = getActors();
var filteredResult = listOfActors.stream()
.filter(person -> person.getAge() > 45)
.collect(Collectors.toList());
System.out.println("Filtered Result:\n"+filteredResult.toString());
}
static List <Actor> getActors() {
List <Actor> actors = new ArrayList <Actor> ();
actors.add(new Actor(5, "yashu"));
actors.add(new Actor(64, "gaurangee"));
actors.add(new Actor(93, "isha"));
actors.add(new Actor(8, "deepak"));
actors.add(new Actor(87, "yashi"));
return actors;
}
}
class Actor {
int age;
String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Actor(int age, String name) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Actor{");
sb.append("name=").append(name);
sb.append(", age=").append(age);
sb.append('}');
return sb.toString();
}
}
Output:
Filtered Result:
[Actor{name=gaurangee, age=64}, Actor{name=isha, age=93}, Actor{name=yashi, age=87}]
Java 8 streams filter example
Java 8 Streams Filter Example...!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Passing Function as a Parameter in another Method in Java 8
- Collection sorting using Lambda in Java 8
- Generate Prime numbers in Java 8
- Java 8 program to calculate average of N numbers
- Reverse a word in a string in Java 8
- Finding prime number using Java 8
- Double the numbers of specified ArrayList using Streams