Search code examples
javajava-streampredicate

Use of Predicate in comparing two list of different type in Java


I have two list of type String and an object (consider Employee). String type list have employee codes. Here I need to check if Employee list have any object of code(attribute) saved in String. Below is my employee class

public class Employee {
  public String code;
  public String id;
  // getters, setters and constructor
}

Here I am able to find whether employees have code saved in the given String List (employeeUserGrpCodes).

public static void main(String[] args) {

    final List<String> employeeUserGrpCodes= Arrays.asList("ABCWelcome","ABCPlatinum","SuperEmployee");

    List<Employee> empList=new ArrayList<Employee>();
    Employee k1= new Employee("KCAEmployee","1");
    Employee k2 = new Employee("ABCWelcome","2");

    empList.add(k1);
    empList.add(k2);

   List<Employee> empListN = empList.stream().filter(i->employeeUserGrpCodes.stream().anyMatch(j->j.equalsIgnoreCase(i.getCode()))).collect(Collectors.toList());
   List<String>newEmpList =  empList.stream().map(a->a.getCode()).collect(Collectors.toList()).stream().filter(employeeUserGrpCodes::contains).collect(Collectors.toList());
   if(!empListN.isEmpty() || !newEmpList.isEmpty())
    {
        System.out.println("Employee have employeeUserGrpCodes");
    }
}

In the above code, both approaches are working that is List 'empListN' and List 'newEmpList'. Is it possible to do the same with the help of Predicates which I can easily put in String 'anymatch' like

Predicate<Employee> isEmpUserGroup = e -> e.getCode().equalsIgnoreCase(employeeUserGrpCodes.stream())
boolean isRequiredEmployee = empList.stream().anyMatch(isEmpUserGroup);

Solution

  • First of all for the purpose of knowing if Employee have employeeUserGrpCodes you don't need the two lists because is empListN is not empty newEmpList won't be as well, so we can use only of the two lists, and then, related with the use of the predicates, you are using them already in the filter expressions, you can have something like this for the empListN list:

    Predicate<Employee> employeePredicate = e -> employeeUserGrpCodes.stream().anyMatch(c -> c.equalsIgnoreCase(e.getCode()));
    List<Employee> empListN = empList.stream().filter(employeePredicate).collect(Collectors.toList());
    

    You can notice that the Predicate is using another predicate as well

    c -> c.equalsIgnoreCase(e.getCode())

    So you can also replace the if condition and avoid using a temporary list if you test your predicate against the employee list like this:

    if (empList.stream().anyMatch(employeePredicate)) {
        System.out.println("Employee have employeeUserGrpCodes");
    }