DEV Community

Cover image for Filtering With Predicate
lou
lou

Posted on

4 2

Filtering With Predicate

In programming, when we have a collection, sometimes we need to filter out the part that meets our requirements and discard the rest.

A detailed example is when we have a list of patient records and we want to get a list of underaged patients.

start by copying this code in a java file

public class FilteringPatients {
    private static List<Patient> patientsList= Arrays.asList(
            new Patient("Norman", 15,210),
            new Patient("kai", 17,195),
            new Patient("Adam", 21,180)
    );
    public static class Patient{
        private String name;
        private int age;
        private int roomNumber;
        public Patient(String n,int a, int nbr) {
            name=n;
            age=a;
            roomNumber=nbr;
        }

        public int getAge() {
            return age;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The requirement here is for the age to be below 18.

 public static List<Patient> filterUnderagedPatients ( List<Patient> patientsList){
        List<Patient> Underaged_Patients= new ArrayList<Patient>();
        for (Patient patient: patientsList) {
            if(patient.getAge()<18)
                Underaged_Patients.add(patient);
        }

        return Underaged_Patients;
    }
Enter fullscreen mode Exit fullscreen mode

we can go about it this way or we can use the filter method.

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

Filter is commonly used to filter a collection of objects.

The accepted parameters of the filter method is Predicate,let's take a closer look at it.

Firstly, Predicate is a functional interface, which means Predicate can be represented by a Lambda expression.

It's functional method is test(Object) which takes in one argument and returns a boolean,It is commonly used to test whether a condition is true or false.

 @FunctionalInterface
public interface Predicate<T
Enter fullscreen mode Exit fullscreen mode

let's take the previous example but this time we'll use the filter method with a predicate

public static class UnderagedPatientsPredicate implements Predicate<Patient> {

        @Override
        public boolean test(Patient patient) {
            return patient.getAge()<18;
        }
    }

        public static List<Patient > filter(Predicate<Patient > predicate){
            List<Patient> Underaged_list= new ArrayList();
            for (Patient patient: patientsList) {
                if(predicate.test(patient))
                    Underaged_list.add(patient);
            }

            return Underaged_list;

        }
Enter fullscreen mode Exit fullscreen mode

let's test this in the main function

 public static void main(String[] args) {
            System.out.println("Using filterUnderagedPatients.");

        for (Patient patient : filterUnderagedPatients(patientsList)
        ) {
            System.out.println(patient);

        }
            System.out.println("Using filter with Predicate.");

        for (Patient patient : filter( new UnderagedPatientsPredicate(), patientsList)
        ) {
            System.out.println(patient);
        }

    }
Enter fullscreen mode Exit fullscreen mode

the result is a list of underaged patients

Using filterUnderagedPatients.
Patient{name='Norman', age=15, roomNumber=210}
Patient{name='kai', age=17, roomNumber=195}
Using filter with Predicate.
Patient{name='Norman', age=15, roomNumber=210}
Patient{name='kai', age=17, roomNumber=195}
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
ayoubsen profile image
Ayoub Senhaji

A simple yet detailed explanation, well done 👍

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay