是否可以根据其他列表中的条目减少列表?
以下是类似的内容:
list1.forEach(l1 -> {
list2.forEach(l2 -> {
if (l1.getId() == l2.getId())
reducedActions.add(l2); // that's the new list where the filtered entries should be add
});
});
编辑:我所怀疑的:
l1: 10, 15, ,16
l2: 1, 2, 12, 10, 11, 14, 16
reducedActions: 10, 16
答案 0 :(得分:6)
这个怎么样?
Set<Integer> ids = list2.stream().map(e -> e.getId()).collect(Collectors.toSet());
List<ElementType> reducedActions = list1.stream().filter(e -> ids.contains(e.getId())).collect(Collectors.toList());
答案 1 :(得分:0)
使用List.retainAll就像:
一样简单List<Integer> list = new ArrayList<Integer>(list2);
list.retainAll(list1);
用法:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReduceList {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(10, 15, 16);
List<Integer> list2 = Arrays.asList(1, 2, 12, 10, 11, 14, 16);
List<Integer> list = new ArrayList<Integer>(list2);
list.retainAll(list1);
System.out.println(list);
}
}