【问题标题】:Use of Predicate in comparing two list of different type in Java使用 Predicate 比较 Java 中不同类型的两个列表
【发布时间】:2020-12-14 20:11:03
【问题描述】:

我有两个字符串类型列表和一个对象(考虑员工)。字符串类型列表有员工代码。在这里,我需要检查员工列表是否有任何代码(属性)对象保存在字符串中。下面是我的员工班

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

在这里我可以找到员工是否将代码保存在给定的字符串列表 (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");
    }
}

在上面的代码中,List 'empListN' 和 List 'newEmpList' 这两种方法都有效。是否可以在 Predicates 的帮助下做同样的事情,我可以很容易地放入 String 'anymatch' like

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

【问题讨论】:

  • 1. collect(Collectors.toList()).stream() 在您的 newEmpList 中是多余的。 2. 尽管有映射,equalsIgnoreCasecontains 之间还是存在细微差别,这在您实际处理区分大小写的输入时会很明显。 3. filter 操作中的 lambda 表达式是 Predicate&lt;T&gt;,其中 T 是 Stream 的类型,在您的情况下为 Employee。 4. 所有这些都可以通过导航到 javadoc 本身来理解。

标签: java java-stream predicate


【解决方案1】:

首先,为了了解 Employee 是否有 employeeUserGrpCodes,您不需要这两个列表,因为 empListN 不为空 newEmpList 也不会,所以我们只能使用这两个列表,然后,与谓词的使用有关,您已经在过滤器表达式中使用它们,您可以在 empListN 列表中使用类似的内容:

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

您可以注意到谓词也在使用另一个谓词

c -&gt; c.equalsIgnoreCase(e.getCode())

因此,如果您像这样针对员工列表测试谓词,您还可以替换 if 条件并避免使用临时列表:

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

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2019-04-22
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2020-10-12
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多