首页 > 代码库 > Java 集合并交补
Java 集合并交补
示例
package com.example;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class ListOpt { private List intersect(List ls1, List ls2) { List list = new ArrayList(Arrays.asList(new Object[ls1.size()])); Collections.copy(list, ls1); list.retainAll(ls2); return list; } private List union(List ls1, List ls2) { List list = new ArrayList(Arrays.asList(new Object[ls1.size()])); Collections.copy(list, ls1); list.addAll(ls2); return list; } private List diff(List ls1, List ls2) { List list = new ArrayList(Arrays.asList(new Object[ls1.size()])); Collections.copy(list, ls1); list.removeAll(ls2); return list; } public static void main(String[] args) { List<Integer> l1 = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; List<Integer> l2 = new ArrayList<Integer>() {{ add(2); add(3); add(4); }}; ListOpt opt = new ListOpt(); List intersectList = opt.intersect(l1, l2); List union = opt.union(l1, l2); List diff = opt.diff(l1, l2); print(intersectList); print(union); print(diff); } private static void print(List lst) { if (lst.size() == 0) { return; } for (int i = 0; i <lst.size(); ++i) { System.out.println(lst.get(i)); } System.out.println("---"); }}
输出
23---123234---1---
注
在操作之前对原对象进行了拷贝,如果对原对象直接操作会修改原来的对象
Java 集合并交补
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。