示例
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("---");
}
}
输出
2
3
---
1
2
3
2
3
4
---
1
---
注
在操作之前对原对象进行了拷贝,如果对原对象直接操作会修改原来的对象
另一种写法
/**
* Created by yuhui on 2017/7/11 0011.
*/
import java.util.HashSet;
import java.util.Set;
public class TestSet {
public static void main(String[] args) {
Set<String> result = new HashSet<String>();
Set<String> set1 = new HashSet<String>() {
{
add("王者荣耀");
add("英雄联盟");
add("穿越火线");
add("地下城与勇士");
}
};
Set<String> set2 = new HashSet<String>() {
{
add("王者荣耀");
add("地下城与勇士");
add("魔兽世界");
}
};
result.clear();
result.addAll(set1);
result.retainAll(set2);
System.out.println("交集:" + result);
result.clear();
result.addAll(set1);
result.removeAll(set2);
System.out.println("差集:" + result);
result.clear();
result.addAll(set1);
result.addAll(set2);
System.out.println("并集:" + result);
}
}