需求 list的方法 说明 备注
交集 listA.retainAll(listB) listA内容变为listA和listB都存在的对象 listB不变
差集 listA.removeAll(listB) listA中存在的listB的内容去重 listB不变
并集 listA.removeAll(listB)
listA.addAll(listB)
为了去重,listA先取差集,然后追加全部的listB listB不变

测试代码:

// 交集
List<String> listA_01 = new ArrayList<String>(){{
    add("A");
    add("B");
}};
List<String> listB_01 = new ArrayList<String>(){{
    add("B");
    add("C");
}};
listA_01.retainAll(listB_01);
System.out.println(listA_01); // 结果:[B]
System.out.println(listB_01); // 结果:[B, C]

// 差集
List<String> listA_02 = new ArrayList<String>(){{
    add("A");
    add("B");
}};
List<String> listB_02 = new ArrayList<String>(){{
    add("B");
    add("C");
}};
listA_02.removeAll(listB_02);
System.out.println(listA_02); // 结果:[A]
System.out.println(listB_02); // 结果:[B, C]

// 并集
List<String> listA_03 = new ArrayList<String>(){{
    add("A");
    add("B");
}};
List<String> listB_03 = new ArrayList<String>(){{
    add("B");
    add("C");
}};
listA_03.removeAll(listB_03);
listA_03.addAll(listB_03);
System.out.println(listA_03); // 结果:[A, B, C]
System.out.println(listB_03); // 结果:[B, C]

相关文章:

  • 2021-07-28
  • 2021-08-17
  • 2021-12-25
  • 2021-11-12
  • 2021-10-21
  • 2021-08-02
  • 2022-12-23
猜你喜欢
  • 2022-02-11
  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案