猿问

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

我正在尝试使用 java 8 来解决以下问题。说我有以下(A并且B是自定义类)


ArrayList<A> skills;

HashSet<B> workCenters;

我需要做的是查找 value a.getDepartment()which is a Stringalso包含在B其中是否也有一个方法String getDepartment(),然后将它们收集到 newList<A>中。


我试过这样:


 List<A> collect = skills.stream()

     .filter(s -> workCenters.contains(s.getDepartment())

     .collect(Collectors.toList());

但在这种情况下,我做得不对,因为我无法getDepartment()从workCenters. 什么是正确的解决方案?


绝地无双
浏览 133回答 3
3回答

犯罪嫌疑人X

您可以先转换HashSet<B>为HashSet<String>然后使用您的代码:Set<String> bDeps = workCenters.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(B::getDepartment)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toSet());List<A> collect = skills.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(s -> bDeps.contains(s.getDepartment()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());

慕斯王

collect比方说,所有部门都workCenters进入了。Set<String>departmentSetList<A>&nbsp;collect&nbsp;=&nbsp;skills.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(s&nbsp;->&nbsp;departmentSet.contains(s.getDepartment()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());

幕布斯7119047

首先流式传输workCenters并获取其中的一组部门,然后流式传输技能并过滤掉该集合中不存在的任何技能。final Set<String> workCenterDepartments = workCenters.stream()&nbsp; &nbsp; .map(B::getDepartment)&nbsp; &nbsp; .collect(Collectors.toSet());final List<A> skillsWithWorkCenterDept = skills.stream()&nbsp; &nbsp; .filter(skill -> workCenterDepartments.contains(skill.getDepartment()))&nbsp; &nbsp; .collect(Collectors.toList());如果您不再需要旧列表,您可能会决定从前一个列表中删除元素,而不是创建一个新列表:skills.removeIf(skill -> !workCenterDepartments.contains(skill.getDepartment()));
随时随地看视频慕课网APP

相关分类

Java
我要回答