Java filter List with Predicate

In this example we will make Java program that filter List with Predicate. is create with positive and negative numbers. Then this list is filter by Stream.filter method which accept predicate as argument. There are three examples:

  • Predicate is written as lambda expression i -> i>=0. At the end the filtered list is collected with toList method
  • Negative Predicate (predicate which filter only negative numbers) is created and then passed as argument
  • Positive Predicate is created from the negation with Predicate.not method and then passed as argument
import java.util.List;
import java.util.function.Predicate;

public class MainFilterList {
    public static void main(String[] args) {
        List<Integer> list = List.of(1, -2, 3, -4, 31, 12, -31);
        System.out.println("Initial list:" + list);

        // Filter only the positive numbers. Predicate is directly written
        List<Integer> positiveNumbers = list.stream().filter(i -> i >= 0).toList();
        System.out.println("Positive list: " + positiveNumbers);

        // Create predicate and then used it to filter negative numbers
        Predicate<Integer> negativeNumbersPredicate = i -> i < 0;
        List<Integer> negativeNumbers = list.stream().filter(negativeNumbersPredicate).toList();
        System.out.println("Negative list: " + negativeNumbers);

        // Create predicate which is opposite to another predicate with Predicate.not
        Predicate<Integer> positiveNumbersPredicate = Predicate.not(negativeNumbersPredicate);
        List<Integer> positiveNumbersAgain = list.stream().filter(positiveNumbersPredicate).toList();
        System.out.println("Positive list: " + positiveNumbersAgain);
    }
}


Output:

Initial list:[1, -2, 3, -4, 31, 12, -31]
Positive list: [1, 3, 31, 12]
Negative list: [-2, -4, -31]
Positive list: [1, 3, 31, 12]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.