28
Feb

Passing Predicates as argument

Passing Predicates as argument:
================================


Step 1:  Create your object class
==================================


public class Student {

	private int rollNo;
	private String name;
	private int dob;

	public Student(int rollNo, String name, int dob) {
		super();
		this.rollNo = rollNo;
		this.name = name;
		this.dob = dob;
	}

	public int getRollNo() {
		return rollNo;
	}

	public String getName() {
		return name;
	}

	public int getDob() {
		return dob;
	}

}


Step 2: Create StudentPredicate class
======================================

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

public class StudentPredicates {

	public static List<Student> filterStudent(List<Student> student, Predicate<Student> predicate) {
		return 	 student.stream()
				.filter(predicate)
				.collect(Collectors.toList());
	}
}



Step 3: client
===============

import java.util.Arrays;
import java.util.List;

public class StudentTest {

	public static void main(String[] args) {
		Student s1 = new Student(1, "JackyChAn", 1);
		Student s2 = new Student(1, "BackyChAn", 1);
		Student s3 = new Student(1, "CackyChAn", 1);

		List<Student> arrL = Arrays.asList(new Student[] {s1, s2, s3});
		
		List<Student> res = StudentPredicates.filterStudent(arrL, x->x.getName().contains("A"));
		
		for(Student s: res)
			System.out.println(s.getName());
		
		res = StudentPredicates.filterStudent(arrL, x -> x.getDob()==1);
		
		for(Student s: res)
			System.out.println(s.getDob());
		
	}

}

Output:
JackyChAn
BackyChAn
CackyChAn
1
1
1




http://defectracker.com/wp-content/uploads/2020/02/Predicate-as-argument.txt