首页 > 编程知识 正文

java两个list取交集,java stream 两个list 匹配 赋值

时间:2023-05-05 13:50:18 阅读:183733 作者:4074

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); }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。