Java實現陣列的交集、並集、差集
阿新 • • 發佈:2019-01-08
/**
* 陣列交集,並集,差集
* @author Administrator
*
*/
public class cal3 {
public static void main(String[] args) {
String[] arr1 = {"abc", "df", "abc"};
String[] arr2 = {"abc", "cc", "df", "d", "abc"};
intersect(arr1, arr2);
}
//並集
public static Set union(String [] arr1, String[] arr2) {
Set<String> set = new HashSet<String>();
for (String str : arr1) {
set.add(str);
}
for (String str : arr2) {
set.add(str);
}
return set;
}
//差集(在陣列A中不在陣列B中)
public static List<String > minus(String[] arr1, String[] arr2) {
LinkedList<String> list = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
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);
}
}
}
return list;
}
//交集
public static List<String> intersect(String[] arr1, String[] arr2) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
LinkedList<String> list = new LinkedList<String>();
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 (Entry<String, Boolean> e : map.entrySet()) {
if (e.getValue().equals(Boolean.TRUE)) {
list.add(e.getKey());
System.out.println(e.getKey());
}
}
return list;
}
}