Java 8 provides an extremely powerful abstract concept Stream
with many useful mechanics for consuming and processing data in Java Collection. In the tutorial, We will use lots of examples to explore more the helpful of Stream API with filtering function on the specific topic: “Filter Collection with Java 8 Stream”.
What will we do?
- How to filter List with traditional approach?
- Use Java 8 Stream to filter List and Array Objects
- Apply
filter()
function with other util functions of Stream API in practice
Now let’s do examples for more details!
Related posts:
– Java – How to find an element in a Java List Object by Examples
– Java 8 Streams
Java Filter List by Traditional Approach with Looping
Before Java 8, for filtering a List Objects, we use the basic approach with looping technical solution.
Looping Example – Filter Integer List
– Example: How to get all even number in a list?
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 7, 10, 11, 16); for(Integer i: intList) { if(i%2==0) { System.out.println(i); } } /* 2 4 10 16 */ |
Looping Example – Filter String List
– Example: How to get all string that contains “Java” sub-string in a string List?
List<String> strList = Arrays.asList("Java", "Python", "Java Stream", "Java Tutorial", "Nodejs Tutorial"); List<String> newStrList = new ArrayList<String>(); for(String str: strList) { if(str.contains("Java")) { newStrList.add(str); } } System.out.println(newStrList); /* [Java, Java Stream, Java Tutorial] */ |
Looping Example – Filter Custom Object List
– Create a Customer
class:
class Customer{ private int id; private String name; private int age; Customer(int id, String name, int age){ this.id = id; this.name = name; this.age = age; } public int getId() { return this.id; } public String getName() { return this.name; } public int getAge() { return this.age; } public String toString() { return String.format("[id=%d, name=%s, age=%d]", id, name, age); } } |
– Looping through a List to filter objects having age >= 18
:
List<Customer> customers = Arrays.asList(new Customer(1, "Jack", 23), new Customer(2, "Mary", 31), new Customer(3, "Peter", 17), new Customer(4, "Harry", 16), new Customer(5,"Joe", 19)); for(Customer customer: customers) { if(customer.getAge() >= 18) { System.out.println(customer); } } /* [id=1, name=Jack, age=23] [id=2, name=Mary, age=31] [id=5, name=Joe, age=19] */ |
Java 8 Stream Filter Examples
With the a powerful concept Stream
of Java 8, we can use the filter()
method to filtering each element from a list.
Signature:
Stream<Integer> java.util.stream.Stream.filter(Predicate<? super Integer> predicate) |
Stream Filter Example with Integer List
– Example:
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 7, 10, 11, 16); List<Integer> newList = intList.stream().filter(i->i%2==0).collect(Collectors.toList()); System.out.println(newList); /* [2, 4, 10, 16] */ |
In above example code, the filter()
method returns a stream. So we need an util collect()
method to transform stream elements into another container such as a List.
Stream Filter Example with String List
– Example:
List<String> strList = Arrays.asList("Java", "Python", "Java Stream", "Java Tutorial", "Nodejs Tutorial"); List<String> newStrList = strList.stream().filter(str -> str.contains("Java")) .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(newStrList); // [JAVA, JAVA STREAM, JAVA TUTORIAL] |
In the above code, We use map()
function of Java 8 Stream to combine with filter()
to help transforms each string after filter to Uppercase.
Stream Filter Example with Custom List
– Example:
List<Customer> customers = Arrays.asList(new Customer(1, "Jack", 23), new Customer(2, "Mary", 31), new Customer(3, "Peter", 17), new Customer(4, "Harry", 16), new Customer(5,"Joe", 19)); customers.stream().filter(c -> c.getAge() >= 18) .forEach(System.out::println); /* [id=1, name=Jack, age=23] [id=2, name=Mary, age=31] [id=5, name=Joe, age=19] */ |
In above example, we use forEach()
terminal operation to performs an action System.out.println()
for each stream element.
We can also combine filter
stream with sorted()
method:
customers.stream().filter(c -> c.getAge() >= 18) .sorted(Comparator.comparing(Customer::getAge)) .forEach(System.out::println); /* [id=5, name=Joe, age=19] [id=1, name=Jack, age=23] [id=2, name=Mary, age=31] */ |
Java 8 Stream Filter with Multi-Condition
Assume We need filter all customers having age less than 30 and be an odd number. How to do it?
-> We have 2 approaches:
– Approach 1: apply multiple checking for multi-conditions in only one filter()
method.
List<Customer> customers = Arrays.asList(new Customer(1, "Jack", 23), new Customer(2, "Mary", 31), new Customer(3, "Peter", 17), new Customer(4, "Harry", 16), new Customer(5,"Joe", 19)); customers.stream().filter(c -> c.getAge() < 30 && c.getAge() %2 == 1) .forEach(System.out::println); /* [id=1, name=Jack, age=23] [id=3, name=Peter, age=17] [id=5, name=Joe, age=19] */ |
– Approach 2: Use multiple filter()
method together:
customers.stream().filter(c -> c.getAge() < 30) .filter(c -> c.getAge() %2 == 1) .forEach(System.out::println); /* [id=1, name=Jack, age=23] [id=3, name=Peter, age=17] [id=5, name=Joe, age=19] */ |
Parallel & Sequential Streams Filter Example
Stream provides a parallel and sequential API processing, so We can combine it with filter()
method to leverage the multiple cores on your computer for performance processing data.
– See below example:
List<Customer> customers = Arrays.asList(new Customer(1, "Jack", 23), new Customer(2, "Mary", 31), new Customer(3, "Peter", 17), new Customer(4, "Harry", 16), new Customer(5,"Joe", 19)); customers.stream() .parallel() .filter(c -> c.getAge() < 30 && c.getAge() %2 == 1) // concurrently filtering .sequential() // switch to sequential processing .map(c -> new Customer(c.getId(), c.getName().toUpperCase(), c.getAge())) .forEach(System.out::println); /* [id=1, name=JACK, age=23] [id=3, name=PETER, age=17] [id=5, name=JOE, age=19] */ |
Stream Filter Array Objects with Java 8
For using stream to filter objects in Array with Java 8, We do 2 steps:
- Create Stream from Array Objects.
- Apply the filtering in stream for Array Objects as the same way we had done with above List Objects.
Example Code:
Arrays.stream(customers) // create Stream from Array Objects .parallel() .filter(c -> c.getAge() < 30 && c.getAge() %2 == 1) // Concurrently Filtering .sequential() // switch to sequential processing .map(c -> new Customer(c.getId(), c.getName().toUpperCase(), c.getAge())) // apply mapping to Upper-Case the Name .forEach(System.out::println); /* [id=1, name=JACK, age=23] [id=3, name=PETER, age=17] [id=5, name=JOE, age=19] */ |
Conclusion
We had done how to use Java 8 Stream Filter with Examples:
- How to Filter Java List before Java 8 with looping approach
- Apply Stream Filter to Integer, String and Custom Object List
- Combine
filter()
method with other methods of Java 8 Stream such as:map()
,sorted()
,forEach()
- Apply Stream Filter to Java Array
- Explore how to use parallel & sequential streams with
filter()
method
Happy Learning! See you later!
887571 66385U never get what u expect u only get what u inspect 819188
Thank you for this Java 8 tutorial!
625754 293227You created some decent points there. I looked on the internet for that problem and located a lot of people will go in addition to with the internet site. 171647
475850 224444The next time I learn a weblog, I hope that it doesnt disappoint me as considerably as this one. I mean, I do know it was my choice to read, nonetheless I truly thought youd have something attention-grabbing to say. All I hear is actually a bunch of whining about something that you could fix for those that werent too busy in search of attention. 487247
940480 455452You produced some decent points there. I looked on-line for any issue and identified most individuals will go in conjunction with together with your internet site. 342374
274862 937953Thank you a great deal for sharing this with all people you actually recognize what you are speaking about! Bookmarked. Please in addition speak more than with my internet website =). We could have a hyperlink alternate arrangement among us! 400132
719734 807726The the next occasion I read a weblog, I actually hope so it doesnt disappoint me about brussels. Come on, man, Yes, it was my option to read, but I just thought youd have some thing fascinating to state. All I hear can be plenty of whining about something which you could fix in case you werent too busy searching for attention. 766081
829739 200278Really informative and great complex body part of articles , now thats user pleasant (:. 169570
960424 444672Bookmarked. Kindly also consult with my web site. 368477
419995 211037hello admin, your internet site pages pattern is simple and clean and i like it. Your articles are remarkable. Remember to keep up the excellent work. Greets.. 349756
230336 987382How can I attract a lot more hits to my composing weblog? 550069
496333 9897One can undertake all sorts of advised excursions with assorted limousine functions. Various offer great courses and many can take clients for just about any ride your bike over the investment banking area, or even for a vacation to new york. ??????? 577894
94845 532708Interested in start up a online business on line denotes revealing your service also providers not only to humans within your town, nevertheless , to numerous future prospects which are cyberspace on several occasions. pays everyday 331701
364347 560310Im so pleased to read this. This is the kind of manual that needs to be given and not the accidental misinformation thats at the other blogs. Appreciate your sharing this best doc. 121237
666640 491425Nowhere on the Internet is there this significantly quality and clear data on this topic. How do I know? I know because Ive searched this topic at length. Thank you. 218222
911827 360763Would adore to perpetually get updated fantastic weblog ! . 68327
640179 430089For anybody who is interested in enviromentally friendly items, may possibly possibly surprise for you the crooks to keep in mind that and earn under a holder just because kind dissolved acquire various liters to important oil to make. day-to-day deal livingsocial discount baltimore washington 26211
722227 391515 You should take part in a contest for among the very best blogs on the internet. I will recommend this website! 533171
7149096645Você conhece o jeito mais tranquilo de aumentar de elo em LOL? Absolutamente, não é se irritando em partidas rankeds. A melhor alternativa é pedir um elo job, um serviço oferecido por um player high elo, com melhor série de vitórias e entre os profissionais do jogo, que aumentará o elo da sua conta.9129126028
9980109008No low elo costumam ficar os jogadores que não conseguem se empenhar com o game, por essa causa, a taxa de desistências no meio das partidas (os AFKs), de mensagens de ira e de feedings é bem maior.4911587688
9370953591No low elo costumam ficar os jogadores frustrados com o game, por essa causa, a taxa de desistências no meio das partidas (os AFKs), de mensagens de hate e de feedings é bem maior.3352601628
4258881189No Ferro, Bronze e Prata costumam ficar os aliados desanimados com o jogo, por esse motivo, a taxa de desistências no meio das partidas (os AFKs), de mensagens de rage e de mortes propositais é bem maior.6013171807
608839297 Se você está achando difícil subir de elo, encontrar alguém que faça um elo job para você ascender está muito fácil. 7295973335
3687497115 Se você tem dificuldade de vencer partidas, encontrar alguém que faça um elojob lol para você ascender está muito fácil. 3303218332
586443664 Se você está achando difícil subir de elo, encontrar uma pessoa que faça um elojob lol para você progredir já é realidade. 3668417811
6821254907 Se você quer muito vencer partidas, encontrar uma pessoa que faça um elo job para você crescer está muito fácil. 1028823461
4832021708 No League of Legends, se um jogador percebe que outro pode ser um elo boost ou um smurf (apelido aqueles que têm contas em elos mais altos, mas jogam em contas com elos mais baixos) é possível informar e fazer com que aquela conta seja testada. Se isso ocorrer, você pode ser banido. 2619458496
puta (boostinha) safada metendo gostoso na elojobmax