public static void main(String[] args) {
TestVo testVo0 = new TestVo("0", "A", "~", "@");
TestVo testVo1 = new TestVo("1", "B", "~", "@");
TestVo testVo2 = new TestVo("2", "C", "~", "@");
TestVo testVo3 = new TestVo("3", "D", "~", "@");
List<TestVo> list1 = new ArrayList<>();
list1.add(testVo0);
list1.add(testVo1);
list1.add(testVo2);
list1.add(testVo3);
TestVo testVo4 = new TestVo("0", "V", "~", "@");
TestVo testVo5 = new TestVo("1", "F", "~", "@");
TestVo testVo6 = new TestVo("4", "C", "~", "@");
TestVo testVo7 = new TestVo("5", "D", "~", "@");
List<TestVo> list2 = new ArrayList<>();
list2.add(testVo4);
list2.add(testVo5);
list2.add(testVo6);
list2.add(testVo7);
//并集(不去重)
List<TestVo> allList1 = list1.parallelStream().collect(Collectors.toList());
List<TestVo> allList2 = list2.parallelStream().collect(Collectors.toList());
List< TestVo> allList = new ArrayList<> ();
allList.addAll(allList1);
allList.addAll(allList2);
System.out.println(allList);
//交集1
List<TestVo> collectVo = list1.stream().filter(item ->
list2.stream().map(TestVo::getId).collect(Collectors.toList()).contains(item.getId())
).collect(Collectors.toList());
collectVo.forEach(System.out::println);
//交集2
List<TestVo> collect = list1.stream().filter(item ->{
for (TestVo tvo1 : list2) {
if (item.getId().equals(tvo1.getId())) {
return true;
}
}
return false;
}).collect(Collectors.toList());
collect.forEach(System.out::println);
//补集
List<TestVo> collectVo2 = list1.stream().filter(testVo -> {
for (TestVo tvo : list2) {
if (testVo.getId().equals(tvo.getId())) {
return false;
}
}
return true;
}).collect(Collectors.toList());
collectVo2.forEach(System.out::println);
}
Stream对两个List求取并集、交集、补集
最新推荐文章于 2023-07-11 20:29:37 发布