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...!!! Click To Tweet
Filter List using ‘Java 8 Streams’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | /** * 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:
1 2 | 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...!!! Click To Tweet
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