DEV Community

loizenai
loizenai

Posted on

Java – How to use Stream Filter in Java 8 with List & Array Examples

https://ozenero.com/java-how-to-use-stream-filter-in-java-8-with-list-array-examples

Java – How to use Stream Filter in Java 8 with List & Array Examples

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 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 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:

More at:

https://ozenero.com/java-how-to-use-stream-filter-in-java-8-with-list-array-examples

Java – How to use Stream Filter in Java 8 with List & Array Examples

Top comments (0)