根据集合中的值过滤列表中的值

时间:2019-01-23 09:42:06

标签: java java-8

我正在尝试使用Java 8解决以下问题。假设我有以下内容(AB是自定义类)

ArrayList<A> skills;
HashSet<B> workCenters;

我需要做的是确定值a.getDepartment()是否也是String所包含的B,它也具有方法String getDepartment(),然后将其收集到新的List<A>

我尝试过:

 List<A> collect = skills.stream()
     .filter(s -> workCenters.contains(s.getDepartment())
     .collect(Collectors.toList());

但是在这种情况下,我做错了,因为我无法从getDepartment()中检索workCenters。什么是正确的解决方案?

4 个答案:

答案 0 :(得分:6)

  1. collectworkCenters中的所有部门变成Set<String>,例如departmentSet
  2. List<A> collect = skills.stream()
                            .filter(s -> departmentSet.contains(s.getDepartment())
                            .collect(Collectors.toList());
    

答案 1 :(得分:6)

您可以先将fab转换为graduation-cap,然后使用您的代码:

HashSet<B>

答案 2 :(得分:5)

首先流经workCenters并获得一组部门,然后流经该技能并过滤掉该组中不存在的任何部门。

final Set<String> workCenterDepartments = workCenters.stream()
    .map(B::getDepartment)
    .collect(Collectors.toSet());

final List<A> skillsWithWorkCenterDept = skills.stream()
    .filter(skill -> workCenterDepartments.contains(skill.getDepartment()))
    .collect(Collectors.toList());

如果您不再需要旧列表,则可以决定从上一个列表中删除元素,而不是创建一个新列表:

skills.removeIf(skill -> !workCenterDepartments.contains(skill.getDepartment()));

答案 3 :(得分:1)

List<B> workCenters = Collections.emptyList();
List<A> skills = Collections.emptyList();

Set<String> workCenterDepartments = workCenters.stream().map(B::getDepartment).collect(Collectors.toSet());
List<A> skillsWithWorkCenterDept = new ArrayList<>(skills);
skillsWithWorkCenterDept.removeIf(skill -> !workCenterDepartments.contains(skill.getDepartment()));