//系统方法
package com;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List list1 =new ArrayList();
list1.add("1111");
list1.add("2222");
list1.add("3333");
List list2 =new ArrayList();
list2.add("3333");
list2.add("4444");
list2.add("5555");
//并集
//list1.addAll(list2);
//交集
//list1.retainAll(list2);
//差集
//list1.removeAll(list2);
//无重复并集
list2.removeAll(list1);
list1.addAll(list2);
Iterator<String> it=list1.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
//System.out.println("-----------------------------------\n");
//printStr(list1);
}
public static void printStr(List list1){
for (int i = 0; i < list1.size(); i++) {
System.out.println(list1.get(i));
}
}
}
//自己模拟
package com.array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet; import java.util.Iterator;
import java.util.List; import java.util.Map; import java.util.Set;
import java.util.Map.Entry;
public class StringArray
{
public static void main(String[] args)
{
// 测试union
String[] arr1 = { "abc" , "df" , "abcd" };
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);
}
System.out.println( "---------------------可爱的分割线------------------------" );
// 测试insect
String[] result_insect = intersect(arr1, arr2);
System.out.println( "求交集的结果如下:" );
for (String str : result_insect)
{
System.out.println(str);
}
System.out.println( "---------------------可爱的分割线------------------------" );
}
// 求两个字符串数组的并集,利用set的元素唯一性
public static String[] 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);
}
String[] result = {};
return set.toArray(result);
}
// 求两个数组的交集
public static String[] intersect(String[] arr1, String[] arr2)
{
Map<String, Boolean> map = new HashMap<String, Boolean>();
List<String> list = new ArrayList<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 (Iterator<Entry<String, Boolean>> it = map.entrySet().iterator();it.hasNext();)
{
Entry<String,Boolean> e = (Entry<String,Boolean>)it.next();
if (e.getValue().equals(Boolean.TRUE))
{
list.add(e.getKey());
}
}
return list.toArray( new String[] {});
}
} |
原文:http://blog.csdn.net/u010552723/article/details/44946395