importjava.util.HashMap;importjava.util.HashSet;importjava.util.LinkedList;importjava.util.Map;importjava.util.Map.Entry;importjava.util.Set;public classStringArray {public static voidmain(String[] args) {//测试union
String[] arr1 = {"abc", "df", "abc"};
String[] arr2= {"abc", "cc", "df", "d", "abc"};
String[] result_union=union(arr1, arr2);
System.out.println("求并集的结果如下:");for(String str : result_union) {
System.out.println(str);
}//测试insect
String[] result_insect =intersect(arr1, arr2);
System.out.println("求交集的结果如下:");for(String str : result_insect) {
System.out.println(str);
}//测试minus
String[] result_minus =minus(arr1, arr2);
System.out.println("求差集的结果如下:");for(String str : result_minus) {
System.out.println(str);
}
}//求两个字符串数组的并集,利用set的元素唯一性
public staticString[] union(String[] arr1, String[] arr2) {
Set set = new HashSet();for(String str : arr1) {
set.add(str);
}for(String str : arr2) {
set.add(str);
}
String[] result={};returnset.toArray(result);
}//求两个数组的交集
public staticString[] intersect(String[] arr1, String[] arr2) {
Map map = new HashMap();
LinkedList list = new LinkedList();for(String str : arr1) {if (!map.containsKey(str)) {
map.put(str, Boolean.FALSE);
}
}for(String str : arr2) {if(map.containsKey(str)) {
map.put(str, Boolean.TRUE);
}
}for (Entrye : map.entrySet()) {if(e.getValue().equals(Boolean.TRUE)) {
list.add(e.getKey());
}
}
String[] result={};returnlist.toArray(result);
}//求两个数组的差集
public staticString[] minus(String[] arr1, String[] arr2) {
LinkedList list = new LinkedList();
LinkedList history = new LinkedList();
String[] longerArr=arr1;
String[] shorterArr=arr2;//找出较长的数组来减较短的数组
if (arr1.length >arr2.length) {
longerArr=arr2;
shorterArr=arr1;
}for(String str : longerArr) {if (!list.contains(str)) {
list.add(str);
}
}for(String str : shorterArr) {if(list.contains(str)) {
history.add(str);
list.remove(str);
}else{if (!history.contains(str)) {
list.add(str);
}
}
}
String[] result={};returnlist.toArray(result);
}
}