Filtering in Streams

  • Last Updated: January 30, 2024
  • By: javahandson
  • Series
img

Filtering in Streams

In this article, we will look at how to achieve filtering in streams with proper examples. If you want to learn more about other Java, Java 8, or Spring concepts then please click the above menu options.

 

filter method

The Stream interface has a filter method that filters the elements in a stream. This filter method takes a predicate as an argument and it returns a new stream including all the elements that match the predicate.

Note* Predicate is used to test a condition and return a boolean value.

Syntax of the filter method

Stream<T> filter(Predicate<? super T> predicate)

Argument : filter method takes a predicate as an argument
Return : A new stream of filtered elements

Write a program to filter the even numbers in a list.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilterElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        Stream<Integer> stream = list.stream().filter((element) -> element % 2 == 0);
        List<Integer> evenNumbers = stream.collect(Collectors.toList());

        System.out.println("Even numbers : "+evenNumbers);
    }
}
Output: Even numbers : [2, 4, 6]

In the above example, we have added a predicate logic directly inside the filter method. But in some cases, the filtering logic can be of multiple statements, in such cases we can separate predicate logic and just pass the predicate reference to the filter method. A sample example is like below.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilterElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        Predicate<Integer> predicate = (element) -> element % 2 == 0;
        Stream<Integer> stream = list.stream().filter(predicate);
        List<Integer> evenNumbers = stream.collect(Collectors.toList());

        System.out.println("Even numbers : "+evenNumbers);
    }
}
Output: Even numbers : [2, 4, 6]

We can combine all the above statements in one line like below.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FilterElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

        List<Integer> evenNumbers = list.stream()
                .filter((element) -> element % 2 == 0)
                .collect(Collectors.toList());

        System.out.println("Even numbers : "+evenNumbers);
    }
}
Output: Even numbers : [2, 4, 6]

filtering unique elements: distinct method

The Stream interface provides a distinct method to filter the unique elements in a stream. The distinct method will remove the duplicates from a stream and return a stream with unique elements.

Note* The elements will be compared according to the implementation of the hashCode and equals methods of the objects.

Syntax of the distinct method

Stream<T> distinct()

Argument : No args
Return : A new stream of unique elements

Write a program to remove the duplicate numbers from a list.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DistinctElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 2, 4, 3, 6);
        Stream<Integer> stream = list.stream().distinct();
        List<Integer> uniqueElements = stream.collect(Collectors.toList());

        System.out.println("Unique Elements : "+uniqueElements);
    }
}
Output: Unique Elements : [1, 2, 3, 4, 5, 6]

Write a program to filter the even numbers and then remove the duplicates.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DistinctElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 2, 4, 3, 6);
        Stream<Integer> stream = list.stream().filter(element -> element % 2 == 0).distinct();
        List<Integer> uniqueElements = stream.collect(Collectors.toList());

        System.out.println("Unique Elements : "+uniqueElements);
    }
}
Output: Unique Elements : [2, 4, 6]

We can combine all the above statements in one line like below.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class DistinctElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 2, 4, 3, 6);

        List<Integer> uniqueElements = list.stream()
                .filter(element -> element % 2 == 0)
                .distinct()
                .collect(Collectors.toList());

        System.out.println("Unique Elements : "+uniqueElements);
    }
}
Output: Unique Elements : [2, 4, 6]

truncating a stream: limit method

The Stream interface provides a method called limit that limits the number of elements in a stream. The limit method will truncate the existing stream and return a new stream such that the number of elements in the new stream should not be more than the maximum size provided.

Syntax of the limit method

Stream<T> limit(long maxSize)

Argument : limit method takes a long as an argument. maxSize specifies the number of elements in the new stream.
Return : A new stream with max size of elements.

Write a program to truncate a stream and return a new stream of size 3.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TruncateElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
        Stream<Integer> stream = list.stream().limit(3);
        List<Integer> truncateElements = stream.collect(Collectors.toList());

        System.out.println("List with only 3 Elements : "+ truncateElements);
    }
}
Output: List with only 3 Elements : [1, 2, 3]

Write a program to filter the even numbers and then return a new stream of size 3.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TruncateElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
        Stream<Integer> stream = list.stream().filter(element -> element % 2 == 0).limit(3);
        List<Integer> truncateElements = stream.collect(Collectors.toList());

        System.out.println("List with only 3 Elements : "+ truncateElements);
    }
}
Output: List with only 3 Elements : [2, 4, 6]

We can combine all the above statements in one line like below.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class TruncateElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);

        List<Integer> truncateElements = list.stream()
                .filter(element -> element % 2 == 0)
                .limit(3)
                .collect(Collectors.toList());

        System.out.println("List with only 3 Elements : "+ truncateElements);
    }
}
Output: List with only 3 Elements : [2, 4, 6]

skipping elements: skip method

The Stream interface provides a method called skip that skips or discards the first n elements of a stream. The skip method will skip the first n elements of the existing stream and return a new stream.

Syntax of the distinct method

Stream<T> skip(long n)

Argument : skip method takes a long as an argument. This specifies the number of first n elements that we have to skip from the new stream.
Return : A new stream with the skipped elements.

Write a program to filter the even numbers and skip the first 3 elements from that filtered stream.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SkippingElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Stream<Integer> stream = list.stream().filter(element -> element % 2 == 0).skip(3);
        List<Integer> truncateElements = stream.collect(Collectors.toList());

        System.out.println("List with skipped elements : "+ truncateElements);
    }
}
Output: List with skipped elements : [8, 10]

We can combine all the above statements in one line like below.

package com.javahandson.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SkippingElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        List<Integer> truncateElements = list.stream()
                .filter(element -> element % 2 == 0)
                .skip(3)
                .collect(Collectors.toList());

        System.out.println("List with skipped elements : "+ truncateElements);
    }
}
Output: List with skipped elements : [8, 10]

So this is all about filtering in streams with proper examples. If you have any questions on this topic please raise them in the comments section. If you liked this article then please share this post with your friends and colleagues so that they can learn about Java and its frameworks in more depth.

Leave a Comment