DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Intercepting Filter Design Pattern in Java
  • Filter or Criteria Design Pattern in Java: An Introduction, Example, and Key points
  • Filtering Java Collections via Annotation-Driven Introspection
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues

Trending

  • Chaos Engineering for Microservices
  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  • How to Convert Between PDF and TIFF in Java
  1. DZone
  2. Coding
  3. Java
  4. Using Filter Design Pattern In Java

Using Filter Design Pattern In Java

How to use filter design pattern in Java—also known as Criteria Design Pattern, which is a structural pattern that combines multiple criteria to obtain single criteria.

By 
Brijesh Saxena user avatar
Brijesh Saxena
DZone Core CORE ·
Oct. 22, 20 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
25.6K Views

Join the DZone community and get the full member experience.

Join For Free

Lets discuss another very useful design pattern named - Filter Design Pattern.

Filter Design Pattern

  • The Filter Design Pattern also known as Criteria Design Pattern.
  • The Filter Design Pattern is a design pattern that allows developers to filter a set of objects using different criteria/filter condition and chaining them in a decoupled way through logical operations. 
  • The Filter Design Pattern is a structural pattern which can combines multiple criteria to obtain single criteria.
  • With the use of Lambda Expressions in Java 8, it is actually very simple to use without even thinking this as a design pattern. But, if we are aware of the concept of filtering, we will have better understanding and command over the implementation of the code.
  • There are two different ways of creating filters
    • Filter for Entire collection.
    • Filter for single member of the collection. 
  • I will try to highlight use of lambda for filtering as well under this article. But this article is not about Java Lambda Expressions. Based on the viewer's response I may write another article to cover basics of lambdas as well. 


class filter design pattern

To come straight to the Filtering Pattern on a collection of objects, let's use the Employee class I have used in the article of Builder Design Pattern. It's not required to use a builder at all for filtering. All we need is a group of objects to filter. I am using just to save some time in writing a good POJO class to make a collection of and do some good examples of filtering. I hope you understood.

Employee Collection Filter using Filter Design Pattern

 Here's the code for the Employee class:

Java
 




x
134


 
1
package org.trishinfotech.filter;
2

          
3
public class Employee {
4

          
5
    private int empNo;
6
    private String name;
7
    private Gender gender;
8
    private Deptt depttName;
9
    private int salary;
10
    private int mgrEmpNo;
11
    private String projectName;
12

          
13
    public Employee(EmployeeBuilder employeeBuilder) {
14
        if (employeeBuilder == null) {
15
            throw new IllegalArgumentException("Please provide employee builder to build employee object.");
16
        }
17
        if (employeeBuilder.empNo <= 0) {
18
            throw new IllegalArgumentException("Please provide valid employee number.");
19
        }
20
        if (employeeBuilder.name == null || employeeBuilder.name.trim().isEmpty()) {
21
            throw new IllegalArgumentException("Please provide employee name.");
22
        }
23
        this.empNo = employeeBuilder.empNo;
24
        this.name = employeeBuilder.name;
25
        this.gender = employeeBuilder.gender;
26
        this.depttName = employeeBuilder.depttName;
27
        this.salary = employeeBuilder.salary;
28
        this.mgrEmpNo = employeeBuilder.mgrEmpNo;
29
        this.projectName = employeeBuilder.projectName;
30
    }
31

          
32
    public int getEmpNo() {
33
        return empNo;
34
    }
35

          
36
    public String getName() {
37
        return name;
38
    }
39

          
40
    public Gender getGender() {
41
        return gender;
42
    }
43

          
44
    public Deptt getDepttName() {
45
        return depttName;
46
    }
47

          
48
    public int getSalary() {
49
        return salary;
50
    }
51

          
52
    public int getMgrEmpNo() {
53
        return mgrEmpNo;
54
    }
55

          
56
    public String getProjectName() {
57
        return projectName;
58
    }
59

          
60
    @Override
61
    public String toString() {
62
        // StringBuilder class also uses Builder Design Pattern with implementation of
63
        // java.lang.Appendable interface
64
        StringBuilder builder = new StringBuilder();
65
        builder.append("Employee [empNo=").append(empNo).append(", name=").append(name).append(", gender=")
66
                .append(gender).append(", depttName=").append(depttName).append(", salary=").append(salary)
67
                .append(", mgrEmpNo=").append(mgrEmpNo).append(", projectName=").append(projectName).append("]");
68
        return builder.toString();
69
    }
70

          
71
    public static class EmployeeBuilder {
72
        private int empNo;
73
        protected String name;
74
        protected Gender gender;
75
        protected Deptt depttName;
76
        protected int salary;
77
        protected int mgrEmpNo;
78
        protected String projectName;
79

          
80
        public EmployeeBuilder() {
81
            super();
82
        }
83

          
84
        public EmployeeBuilder empNo(int empNo) {
85
            this.empNo = empNo;
86
            return this;
87
        }
88

          
89
        public EmployeeBuilder name(String name) {
90
            this.name = name;
91
            return this;
92
        }
93

          
94
        public EmployeeBuilder gender(Gender gender) {
95
            this.gender = gender;
96
            return this;
97
        }
98

          
99
        public EmployeeBuilder depttName(Deptt depttName) {
100
            this.depttName = depttName;
101
            return this;
102
        }
103

          
104
        public EmployeeBuilder salary(int salary) {
105
            this.salary = salary;
106
            return this;
107
        }
108

          
109
        public EmployeeBuilder mgrEmpNo(int mgrEmpNo) {
110
            this.mgrEmpNo = mgrEmpNo;
111
            return this;
112
        }
113

          
114
        public EmployeeBuilder projectName(String projectName) {
115
            this.projectName = projectName;
116
            return this;
117
        }
118

          
119
        public Employee build() {
120
            Employee emp = null;
121
            if (validateEmployee()) {
122
                emp = new Employee(this);
123
            } else {
124
                System.out.println("Sorry! Employee objects can't be build without required details");
125
            }
126
            return emp;
127
        }
128

          
129
        private boolean validateEmployee() {
130
            return (empNo > 0 && name != null && !name.trim().isEmpty());
131
        }
132
    }
133
}
134

          


I have added a gender field and also changed depttName to enum for writing filter conditions clearly. So let's define the enums as well.

Here's the code for Gender enum:

Java
 




xxxxxxxxxx
1


 
1
package org.trishinfotech.filter;
2

          
3
public enum Gender {
4

          
5
    MALE, FEMALE;
6
}
7

          


Here's the code for Deptt enum:

Java
 




xxxxxxxxxx
1


 
1
package org.trishinfotech.filter;
2

          
3
public enum Deptt {
4

          
5
    ENG, QA, HR, SUPPORT, IT, ADMIN 
6
}
7

          


Example 1: By Using Filter For Entire Collection

In this way we accept the entire collection and return back the collection by eliminating the members which are not applicable as per the filter condition.

Now, lets write an interface named Filter to implement different filter condition or criteria:

Java
 




xxxxxxxxxx
1


 
1
package org.trishinfotech.filter;
2

          
3
import java.util.List;
4

          
5
public interface Filter {
6

          
7
    public List<Employee> apply(List<Employee> employees);
8
}
9

          


Here's the code for MaleFilter class:

Java
 




xxxxxxxxxx
1
26


 
1
package org.trishinfotech.filter.example1;
2

          
3
import java.util.ArrayList;
4
import java.util.List;
5

          
6
import org.trishinfotech.filter.Employee;
7
import org.trishinfotech.filter.Gender;
8

          
9
public class MaleFilter implements Filter {
10

          
11
    @Override
12
    public List<Employee> apply(List<Employee> employees) {
13
        // implementing in old way
14
        List<Employee> filteredEmployees = new ArrayList<Employee>();
15
        if (employees != null) {
16
            for (Employee employee : employees) {
17
                if (Gender.MALE.equals(employee.getGender())) {
18
                    filteredEmployees.add(employee);
19
                }
20
            }
21
        }
22
        return filteredEmployees;
23
    }
24

          
25
}
26

          


Here's the code for EngFilter class:

Java
 




xxxxxxxxxx
1
24


 
1
package org.trishinfotech.filter.example1;
2

          
3
import java.util.ArrayList;
4
import java.util.List;
5
import java.util.stream.Collectors;
6

          
7
import org.trishinfotech.filter.Deptt;
8
import org.trishinfotech.filter.Employee;
9

          
10
public class EngFilter implements Filter {
11

          
12
    @Override
13
    public List<Employee> apply(List<Employee> employees) {
14
        List<Employee> filteredEmployees = new ArrayList<Employee>();
15
        // implementing using lambda expressions
16
        if (employees != null) {
17
            filteredEmployees.addAll(employees.stream().filter(employee -> Deptt.ENG.equals(employee.getDepttName()))
18
                    .collect(Collectors.toList()));
19
        }
20
        return filteredEmployees;
21
    }
22

          
23
}
24

          


Lets write two more filter for combining any two filter via 'And Condition' or 'Or Condition'.

Here's the code for AndFilter class:

Java
 




xxxxxxxxxx
1
25


 
1
package org.trishinfotech.filter.example1;
2

          
3
import java.util.List;
4

          
5
import org.trishinfotech.filter.Employee;
6

          
7
public class AndFilter implements Filter {
8

          
9
    private Filter filter;
10
    private Filter anotherFilter;
11

          
12
    public AndFilter(Filter filter, Filter anotherFilter) {
13
        this.filter = filter;
14
        this.anotherFilter = anotherFilter;
15
    }
16

          
17
    @Override
18
    public List<Employee> apply(List<Employee> employees) {
19
        List<Employee> firstFilteredEmployees = filter.apply(employees);
20
        List<Employee> secondFilterEmployees = anotherFilter.apply(firstFilteredEmployees);
21
        return secondFilterEmployees;
22
    }
23
    
24
}
25

          


Here's the code for OrFilter class:

Java
 




xxxxxxxxxx
1
33


 
1
package org.trishinfotech.filter.example1;
2

          
3
import java.util.ArrayList;
4
import java.util.List;
5

          
6
import org.trishinfotech.filter.Employee;
7

          
8
public class OrFilter implements Filter {
9

          
10
    private Filter filter;
11
    private Filter anotherFilter;
12

          
13
    public OrFilter(Filter Filter, Filter anotherFilter) {
14
        this.filter = Filter;
15
        this.anotherFilter = anotherFilter;
16
    }
17

          
18
    @Override
19
    public List<Employee> apply(List<Employee> employees) {
20
        List<Employee> firstFilteredEmployees = filter.apply(employees);
21
        List<Employee> secondFilterEmployees = anotherFilter.apply(firstFilteredEmployees);
22
        // now lets make or Filter.
23
        // first copy all first Filter filtered employees.
24
        // now add all second Filter filtered employees which are NOT already in the list
25
        // via first Filter employees.
26
        List<Employee> orFilteredEmployees = new ArrayList<Employee>(firstFilteredEmployees);
27
        secondFilterEmployees.removeAll(firstFilteredEmployees);
28
        orFilteredEmployees.addAll(secondFilterEmployees);
29
        return orFilteredEmployees;
30
    }
31
    
32
}
33

          


Now lets write Main class to execute and test the output:

Java
 




xxxxxxxxxx
1
51


 
1
package org.trishinfotech.filter.example1;
2

          
3
import java.util.Arrays;
4
import java.util.List;
5

          
6
import org.trishinfotech.filter.Deptt;
7
import org.trishinfotech.filter.Employee;
8
import org.trishinfotech.filter.Gender;
9

          
10
public class Main {
11

          
12
    public static void main(String[] args) {
13
        List<Employee> employees = Arrays.asList(
14
                new Employee.EmployeeBuilder().empNo(101).name("Brijesh").gender(Gender.MALE).depttName(Deptt.ENG)
15
                        .salary(140000).projectName("Builder Pattern").build(),
16
                new Employee.EmployeeBuilder().empNo(102).name("Racheal").gender(Gender.FEMALE).depttName(Deptt.ENG)
17
                        .salary(90000).projectName("Factory Pattern").build(),
18
                new Employee.EmployeeBuilder().empNo(103).name("Kim").gender(Gender.MALE).depttName(Deptt.HR)
19
                        .salary(150000).projectName("Editorial").build(),
20
                new Employee.EmployeeBuilder().empNo(104).name("Micheal").gender(Gender.FEMALE).depttName(Deptt.ENG)
21
                        .salary(80000).projectName("Decorator Pattern").build(),
22
                new Employee.EmployeeBuilder().empNo(105).name("Martin").gender(Gender.MALE).depttName(Deptt.SUPPORT)
23
                        .salary(65000).projectName("Web Management").build(),
24
                new Employee.EmployeeBuilder().empNo(106).name("Pierce").gender(Gender.MALE).depttName(Deptt.HR)
25
                        .salary(130000).projectName("Audit").build(),
26
                new Employee.EmployeeBuilder().empNo(107).name("Anjali").gender(Gender.FEMALE).depttName(Deptt.ENG)
27
                        .salary(60000).projectName("State Pattern").build(),
28
                new Employee.EmployeeBuilder().empNo(108).name("Angelina").gender(Gender.FEMALE).depttName(Deptt.ENG)
29
                        .salary(70000).projectName("Flyweight Pattern").build(),
30
                new Employee.EmployeeBuilder().empNo(109).name("Hemant").gender(Gender.MALE).depttName(Deptt.HR)
31
                        .salary(170000).projectName("Audit").build(),
32
                new Employee.EmployeeBuilder().empNo(110).name("Mike").gender(Gender.MALE).depttName(Deptt.IT)
33
                        .salary(150000).projectName("Networking").build());
34

          
35
        System.out.println("Print all employees...");
36
        printEmployees(employees);
37
        List<Employee> maleEmployees = (new MaleFilter().apply(employees));
38
        System.out.println("Print all Male employees...");
39
        printEmployees(maleEmployees);
40
        List<Employee> maleEngEmployees = (new AndFilter(new MaleFilter(), new EngFilter()).apply(employees));
41
        System.out.println("Print all Male And ENG employees...");
42
        printEmployees(maleEngEmployees);
43
    }
44

          
45
    private static void printEmployees(List<Employee> employees) {
46
        System.out.println("======================================================================");
47
        employees.stream().forEach(employee -> System.out.println(employee));
48
        System.out.println("======================================================================");
49
    }
50
}
51

          


Below is the output:

Java
 




xxxxxxxxxx
1
27


 
1
Print all employees...
2
======================================================================
3
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
4
Employee [empNo=102, name=Racheal, gender=FEMALE, depttName=ENG, salary=90000, mgrEmpNo=0, projectName=Factory Pattern]
5
Employee [empNo=103, name=Kim, gender=MALE, depttName=HR, salary=150000, mgrEmpNo=0, projectName=Editorial]
6
Employee [empNo=104, name=Micheal, gender=FEMALE, depttName=ENG, salary=80000, mgrEmpNo=0, projectName=Decorator Pattern]
7
Employee [empNo=105, name=Martin, gender=MALE, depttName=SUPPORT, salary=65000, mgrEmpNo=0, projectName=Web Management]
8
Employee [empNo=106, name=Pierce, gender=MALE, depttName=HR, salary=130000, mgrEmpNo=0, projectName=Audit]
9
Employee [empNo=107, name=Anjali, gender=FEMALE, depttName=ENG, salary=60000, mgrEmpNo=0, projectName=State Pattern]
10
Employee [empNo=108, name=Angelina, gender=FEMALE, depttName=ENG, salary=70000, mgrEmpNo=0, projectName=Flyweight Pattern]
11
Employee [empNo=109, name=Hemant, gender=MALE, depttName=HR, salary=170000, mgrEmpNo=0, projectName=Audit]
12
Employee [empNo=110, name=Mike, gender=MALE, depttName=IT, salary=150000, mgrEmpNo=0, projectName=Networking]
13
======================================================================
14
Print all Male employees...
15
======================================================================
16
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
17
Employee [empNo=103, name=Kim, gender=MALE, depttName=HR, salary=150000, mgrEmpNo=0, projectName=Editorial]
18
Employee [empNo=105, name=Martin, gender=MALE, depttName=SUPPORT, salary=65000, mgrEmpNo=0, projectName=Web Management]
19
Employee [empNo=106, name=Pierce, gender=MALE, depttName=HR, salary=130000, mgrEmpNo=0, projectName=Audit]
20
Employee [empNo=109, name=Hemant, gender=MALE, depttName=HR, salary=170000, mgrEmpNo=0, projectName=Audit]
21
Employee [empNo=110, name=Mike, gender=MALE, depttName=IT, salary=150000, mgrEmpNo=0, projectName=Networking]
22
======================================================================
23
Print all Male And ENG employees...
24
======================================================================
25
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
26
======================================================================
27

          


Example 2: By Using Filter For Single Member of the Collection

In this way we accept a member of the collection in the filter and validate it to know whether the member is satisfying the filter condition or criteria or not.

Here's the code for Filter interface:

Java
 




xxxxxxxxxx
1


 
1
package org.trishinfotech.filter.example2;
2

          
3
import org.trishinfotech.filter.Employee;
4

          
5
public interface Filter {
6

          
7
    public boolean apply(Employee employees);
8
}
9

          


Here's the code for MaleFilter class:

Java
 




xxxxxxxxxx
1
15


 
1
package org.trishinfotech.filter.example2;
2

          
3
import org.trishinfotech.filter.Employee;
4
import org.trishinfotech.filter.Gender;
5

          
6
public class MaleFilter implements Filter {
7

          
8
    @Override
9
    public boolean apply(Employee employee) {
10
        return (employee != null && Gender.MALE.equals(employee.getGender()));
11
    }
12

          
13
}
14

          


Here's the code for MinSalaryFilter class:

Java
 




xxxxxxxxxx
1
20


 
1
package org.trishinfotech.filter.example2;
2

          
3
import org.trishinfotech.filter.Employee;
4

          
5
public class MinSalaryFilter implements Filter {
6

          
7
    private int minSalary;
8
    
9
    public MinSalaryFilter(int minSalary) {
10
        super();
11
        this.minSalary = minSalary;
12
    }
13

          
14
    @Override
15
    public boolean apply(Employee employee) {
16
        return (employee != null && employee.getSalary() >= minSalary);
17
    }
18

          
19
}
20

          


Similarly, Here's the for AndFilter class:

Java
 




xxxxxxxxxx
1
23


 
1
package org.trishinfotech.filter.example2;
2

          
3
import org.trishinfotech.filter.Employee;
4

          
5
public class AndFilter implements Filter {
6

          
7
    private Filter filter;
8
    private Filter anotherFilter;
9

          
10
    public AndFilter(Filter filter, Filter anotherFilter) {
11
        this.filter = filter;
12
        this.anotherFilter = anotherFilter;
13
    }
14

          
15
    @Override
16
    public boolean apply(Employee employee) {
17
        boolean firstFilter = filter.apply(employee);
18
        boolean secondFilter = anotherFilter.apply(employee);
19
        return firstFilter && secondFilter;
20
    }
21
    
22
}
23

          


And here's the code for OrFilter class:

Java
 




xxxxxxxxxx
1
23


 
1
package org.trishinfotech.filter.example2;
2

          
3
import org.trishinfotech.filter.Employee;
4

          
5
public class OrFilter implements Filter {
6

          
7
    private Filter filter;
8
    private Filter anotherFilter;
9

          
10
    public OrFilter(Filter Filter, Filter anotherFilter) {
11
        this.filter = Filter;
12
        this.anotherFilter = anotherFilter;
13
    }
14

          
15
    @Override
16
    public boolean apply(Employee employee) {
17
        boolean firstFilter = filter.apply(employee);
18
        boolean secondFilter = anotherFilter.apply(employee);
19
        return firstFilter || secondFilter;
20
    }
21
    
22
}
23

          


Simpler! Well yes it is since the collection traversing is moved to client application (Main class in our example)

Now lets write our Main class to execute and test the output:

Java
 




x


 
1
package org.trishinfotech.filter.example2;
2

          
3
import java.util.Arrays;
4
import java.util.List;
5
import java.util.stream.Collectors;
6

          
7
import org.trishinfotech.filter.Deptt;
8
import org.trishinfotech.filter.Employee;
9
import org.trishinfotech.filter.Gender;
10

          
11
public class Main {
12

          
13
    public static void main(String[] args) {
14
        List<Employee> employees = Arrays.asList(
15
                new Employee.EmployeeBuilder().empNo(101).name("Brijesh").gender(Gender.MALE).depttName(Deptt.ENG)
16
                        .salary(140000).projectName("Builder Pattern").build(),
17
                new Employee.EmployeeBuilder().empNo(102).name("Racheal").gender(Gender.FEMALE).depttName(Deptt.ENG)
18
                        .salary(90000).projectName("Factory Pattern").build(),
19
                new Employee.EmployeeBuilder().empNo(103).name("Kim").gender(Gender.MALE).depttName(Deptt.HR)
20
                        .salary(150000).projectName("Editorial").build(),
21
                new Employee.EmployeeBuilder().empNo(104).name("Micheal").gender(Gender.FEMALE).depttName(Deptt.ENG)
22
                        .salary(80000).projectName("Decorator Pattern").build(),
23
                new Employee.EmployeeBuilder().empNo(105).name("Martin").gender(Gender.MALE).depttName(Deptt.SUPPORT)
24
                        .salary(65000).projectName("Web Management").build(),
25
                new Employee.EmployeeBuilder().empNo(106).name("Pierce").gender(Gender.MALE).depttName(Deptt.HR)
26
                        .salary(130000).projectName("Audit").build(),
27
                new Employee.EmployeeBuilder().empNo(107).name("Anjali").gender(Gender.FEMALE).depttName(Deptt.ENG)
28
                        .salary(60000).projectName("State Pattern").build(),
29
                new Employee.EmployeeBuilder().empNo(108).name("Angelina").gender(Gender.FEMALE).depttName(Deptt.ENG)
30
                        .salary(70000).projectName("Flyweight Pattern").build(),
31
                new Employee.EmployeeBuilder().empNo(109).name("Hemant").gender(Gender.MALE).depttName(Deptt.HR)
32
                        .salary(170000).projectName("Audit").build(),
33
                new Employee.EmployeeBuilder().empNo(110).name("Mike").gender(Gender.MALE).depttName(Deptt.IT)
34
                        .salary(150000).projectName("Networking").build());
35

          
36
        System.out.println("Print all employees...");
37
        printEmployees(employees);
38
        List<Employee> maleEmployees = applyFilter(new MaleFilter(), employees);
39
        System.out.println("Print all Male employees...");
40
        printEmployees(maleEmployees);
41
        List<Employee> maleEngEmployees = applyFilter(new AndFilter(new MaleFilter(), new MinSalaryFilter(140000)), employees);
42
        System.out.println("Print all Male And Min Salary 140000 employees...");
43
        printEmployees(maleEngEmployees);
44
        // now lets try the same with the help of Java Lambda Expressions...
45
        System.out.println("\n\n\nnow lets try the same with the help of Java Lambda Expressions...");
46
        List<Employee> maleEmployeesUsingLambda = employees.stream()
47
                .filter(employee -> Gender.MALE.equals(employee.getGender())).collect(Collectors.toList());
48
        System.out.println("Print all Male employees using lambda...");
49
        printEmployees(maleEmployeesUsingLambda);
50
        List<Employee> maleEngEmployeesUsingLambda = employees.stream()
51
                .filter(employee -> Gender.MALE.equals(employee.getGender()))
52
                .filter(employee -> Deptt.ENG.equals(employee.getDepttName())).collect(Collectors.toList());
53
        System.out.println("Print all Male And ENG employees using lambda...");
54
        printEmployees(maleEngEmployeesUsingLambda);
55
    }
56

          
57
    private static List<Employee> applyFilter(Filter filter, List<Employee> employees) {
58
        return employees.stream().filter(employee -> filter.apply(employee)).collect(Collectors.toList());
59
    }
60

          
61
    private static void printEmployees(List<Employee> employees) {
62
        System.out.println("======================================================================");
63
        employees.stream().forEach(employee -> System.out.println(employee));
64
        System.out.println("======================================================================");
65
    }
66
}
67

          


And below is the output: 

Java
 




xxxxxxxxxx
1
47


 
1
Print all employees...
2
======================================================================
3
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
4
Employee [empNo=102, name=Racheal, gender=FEMALE, depttName=ENG, salary=90000, mgrEmpNo=0, projectName=Factory Pattern]
5
Employee [empNo=103, name=Kim, gender=MALE, depttName=HR, salary=150000, mgrEmpNo=0, projectName=Editorial]
6
Employee [empNo=104, name=Micheal, gender=FEMALE, depttName=ENG, salary=80000, mgrEmpNo=0, projectName=Decorator Pattern]
7
Employee [empNo=105, name=Martin, gender=MALE, depttName=SUPPORT, salary=65000, mgrEmpNo=0, projectName=Web Management]
8
Employee [empNo=106, name=Pierce, gender=MALE, depttName=HR, salary=130000, mgrEmpNo=0, projectName=Audit]
9
Employee [empNo=107, name=Anjali, gender=FEMALE, depttName=ENG, salary=60000, mgrEmpNo=0, projectName=State Pattern]
10
Employee [empNo=108, name=Angelina, gender=FEMALE, depttName=ENG, salary=70000, mgrEmpNo=0, projectName=Flyweight Pattern]
11
Employee [empNo=109, name=Hemant, gender=MALE, depttName=HR, salary=170000, mgrEmpNo=0, projectName=Audit]
12
Employee [empNo=110, name=Mike, gender=MALE, depttName=IT, salary=150000, mgrEmpNo=0, projectName=Networking]
13
======================================================================
14
Print all Male employees...
15
======================================================================
16
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
17
Employee [empNo=103, name=Kim, gender=MALE, depttName=HR, salary=150000, mgrEmpNo=0, projectName=Editorial]
18
Employee [empNo=105, name=Martin, gender=MALE, depttName=SUPPORT, salary=65000, mgrEmpNo=0, projectName=Web Management]
19
Employee [empNo=106, name=Pierce, gender=MALE, depttName=HR, salary=130000, mgrEmpNo=0, projectName=Audit]
20
Employee [empNo=109, name=Hemant, gender=MALE, depttName=HR, salary=170000, mgrEmpNo=0, projectName=Audit]
21
Employee [empNo=110, name=Mike, gender=MALE, depttName=IT, salary=150000, mgrEmpNo=0, projectName=Networking]
22
======================================================================
23
Print all Male And Min Salary 140000 employees...
24
======================================================================
25
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
26
Employee [empNo=103, name=Kim, gender=MALE, depttName=HR, salary=150000, mgrEmpNo=0, projectName=Editorial]
27
Employee [empNo=109, name=Hemant, gender=MALE, depttName=HR, salary=170000, mgrEmpNo=0, projectName=Audit]
28
Employee [empNo=110, name=Mike, gender=MALE, depttName=IT, salary=150000, mgrEmpNo=0, projectName=Networking]
29
======================================================================
30

          
31

          
32

          
33
now lets try the same with the help of Java Lambda Expressions...
34
Print all Male employees using lambda...
35
======================================================================
36
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
37
Employee [empNo=103, name=Kim, gender=MALE, depttName=HR, salary=150000, mgrEmpNo=0, projectName=Editorial]
38
Employee [empNo=105, name=Martin, gender=MALE, depttName=SUPPORT, salary=65000, mgrEmpNo=0, projectName=Web Management]
39
Employee [empNo=106, name=Pierce, gender=MALE, depttName=HR, salary=130000, mgrEmpNo=0, projectName=Audit]
40
Employee [empNo=109, name=Hemant, gender=MALE, depttName=HR, salary=170000, mgrEmpNo=0, projectName=Audit]
41
Employee [empNo=110, name=Mike, gender=MALE, depttName=IT, salary=150000, mgrEmpNo=0, projectName=Networking]
42
======================================================================
43
Print all Male And ENG employees using lambda...
44
======================================================================
45
Employee [empNo=101, name=Brijesh, gender=MALE, depttName=ENG, salary=140000, mgrEmpNo=0, projectName=Builder Pattern]
46
======================================================================
47

          


You know what? by using Java 8 or higher, we even do not need to define our filter at all and can create filter conditions by using Java Predicate as we did in our Main while using lambdas.

Well, that all! I hope this tutorial helped to understand the Filter pattern.

Source Code can be found here: Filter-Design-Pattern-Source-Code

Let me know if you like to have an article on Lambda expressions as well? I will try to write the one if you want. :)

Liked the article? Please don't forget to press that like button. Happy coding!

Need more articles on Design Patterns? Please visit my profile to find more: Brijesh Saxena

Filter (software) Java (programming language) Design

Opinions expressed by DZone contributors are their own.

Related

  • Intercepting Filter Design Pattern in Java
  • Filter or Criteria Design Pattern in Java: An Introduction, Example, and Key points
  • Filtering Java Collections via Annotation-Driven Introspection
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!