0

I have a SearchCriteria POJO class

public class SearchCriteria{

private int empId;
private String empName;
private String empAddress;
private String empDesignation,
:
: 
//getter + setters
}

I have a returnAllEmployees method in other class

public List<Employees> returnAllEmployees (){
// makes a db call which has lot of joins and returns info for all the employees
}

now my question is I have to filter out the result of returnAllEmployees() based on the search criteria passed i.e. if empName field of searchcriteria is populated as "ABC", the filter list should contain details of all the employees as ABC.

Similarly, if search criteria contains empName="ABC" and empDesignation="engineer", it should filter out the list containing all the employees having name abc and designation as engineer

I know it is possible by using if-else but that would create a lot of lines of codes

Sunny
  • 91
  • 1
  • 13

1 Answers1

1

Your best solution is to use Java 8 streams. They are perfect for this:

List<Employee> listOfEngineersCalledFred = getAllEmployees().stream()
    .filter(emp -> emp.getName().equals("Fred"))
    .filter(emp -> emp.getDesignation().equals("Engineer"))
    .collect(Collectors.toList());

A technique that I personally find useful and neat is to add static methods that return predicates instead of using getters:

class Employee {
    public static Predicate<Employee> hasName(String name) {
        return emp -> emp.name.equals(name);
    }
}

These can then be used, for example, to find all employees not call Fred:

streamAllEmployees()
    .filter(Employee.hasName("Fred").negate())
    ...

Which seems neater and more deliberate than exposing the field with a getter.

You also might consider converting your getAllEmployees to streamAllEmployees:

public Stream<Employee> streamAllEmployees() {
    return employeeList.stream();
}

Then you are telling the user they can do things with the employee objects in the list rather than the list itself.

The nice thing about returning it as a stream is that once you have filtered it you can easily count, group, sort, remove duplicates, get first n etc. You can even trivially convert it to use multiple threads if you are filtering large numbers of items.

For example:

Map<String, Employee> employeesByDesignation = streamAllEmployees()
    .collect(Collectors.groupingBy(emp -> emp.getDesignation()));

They are very powerful and worth learning and using.

sprinter
  • 27,148
  • 6
  • 47
  • 78