/**
* function: 将两个集合{“a”,“b”,“c”,“d”,“e”}
* 和{“d”,“e”,“f”,“g”,“h”},把这两个集合去除重复项合并成一个,实现需求。
* author:wangpeng
* time:2018年8月15日上午10:23:27
*/
//Set集合
@Test
public void test2() {
String[] str1={"a","b","c","d","e"};
String[] str2={"d","e","f","g","h"};
Set<String> set1 = new HashSet<String>(Arrays.asList(str1));
Set<String> set2 = new HashSet<String>(Arrays.asList(str2));
Set<String> set = new HashSet<String>();
// 并集
set.addAll(set1);
set.addAll(set2);
System.out.println("并集" + set);
// 交集
set.clear();
set.addAll(set1);
set.retainAll(set2);
System.out.println("交集" + set);
// 差集
set.clear();
set.addAll(set1);
set.removeAll(set2);
System.out.println("差集" + set);
}
//List集合
@Test
public void test3() {
String[] str1 = { "a", "b", "c", "d", "e" };
String[] str2 = { "d", "e", "f", "g", "h" };
ArrayList<String> list1 = new ArrayList<String>(Arrays.asList(str1));
ArrayList<String> list2 = new ArrayList<String>(Arrays.asList(str2));
ArrayList<String> list = new ArrayList<String>();
// 并集
list.addAll(list1);
for (int i = 0; i < list2.size(); i++) {
if (!list.contains(list2.get(i)))
list.add(list2.get(i));
}
System.out.println("并集" + list);
// 交集
list.clear();
for (int i = 0; i < list2.size(); i++) {
if (list1.contains(list2.get(i)))
list.add(list2.get(i));
}
System.out.println("交集" + list);
// 差集
list.clear();
for (int i = 0; i < list1.size(); i++) {
if (!list2.contains(list1.get(i)))
list.add(list1.get(i));
}
System.out.println("差集" + list);
}