import java.util.*;
/**
* 两个集合,去重
*/
public class ElementInList {
/**
* 去除两个集合中重复的元素
*
* @param la
* @param lb
* @param <T>
* @return
*/
public synchronized <T extends Comparable<T>> boolean isEqual(List<T> la, List<T> lb) {
if (la.size() != lb.size())
return false;
Collections.sort(la);
Collections.sort(lb);
for (int i = 0; i < la.size(); i++) {
if (la.get(i) != lb.get(i)) ;
return false;
}
return false;
}
public static ArrayList<String> getDiffElement(List<String> la, List<String> lb) {
int size = la.size() + lb.size();
final Integer flagUnique = 1;
Map<String, Integer> map = new HashMap<String, Integer>(size);
ArrayList<String> newList = new ArrayList<String>();
for (String str : la) {
map.put(str, flagUnique);
}
for (String str : lb) {
Integer value = map.get(str);
if (value != null) {
map.put(str, ++value);
continue;
} else {
map.put(str, flagUnique);
}
}
for (Map.Entry<String, Integer> set : map.entrySet()) {
if (set.getValue() == flagUnique) {
newList.add(set.getKey());
}
}
return newList;
}
public static void main(String[] args) {
ArrayList<String> la = new ArrayList<String>();
la.add("a");
la.add("b");
la.add("d");
la.add("f");
la.add("e");
ArrayList<String> lb = new ArrayList<String>();
lb.add("i");
lb.add("l");
lb.add("o");
lb.add("v");
lb.add("e");
ArrayList<String> diffList = new ArrayList<String>();
diffList = getDiffElement(la, lb);
for (String str : diffList) {
System.out.println(str);
}
}
}
运行结果
a
b
d
f
v
i
l
o