2个数组中,遍历出不同的元素:
public <T> List<T> compareList(List<T> t1, List<T> t2) {
List<T> listMax;
List<T> listMin;
if (t1.size() > t2.size()) {
listMax = t1;
listMin = t2;
} else {
listMax = t2;
listMin = t1;
}
List<T> result = new ArrayList<T>();
for (T t : listMax) {
if (!listMin.contains(t)) {
result.add(t);
}
}
return result;
}
public <T> List<T> compare(T[] t1, T[] t2) {
List<T> listMax;
List<T> listMin;
if (t1.length > t2.length) {
listMax = Arrays.asList(t1);
listMin = Arrays.asList(t2);
} else {
listMax = Arrays.asList(t2);
listMin = Arrays.asList(t1);
}
List<T> result = new ArrayList<T>();
for (T t : listMax) {
if (!listMin.contains(t)) {
result.add(t);
}
}
return result;
}
2个数组 遍历出相同的元素
public static Set<Integer> getIds(Integer[] a, Integer[] b){
Set<Integer> same = new HashSet<Integer>(); //用来存放两个数组中相同的元素
Set<Integer> temp = new HashSet<Integer>(); //用来存放数组a中的元素
for (int i = 0; i < a.length; i++) {
temp.add(a[i]); //把数组a中的元素放到Set中,可以去除重复的元素
}
for (int j = 0; j < b.length; j++) {
//把数组b中的元素添加到temp中
//如果temp中已存在相同的元素,则temp.add(b[j])返回false
if(!temp.add(b[j]))
same.add(b[j]);
}
return same;
}
/**
* 取两个集合的交集
*
* @param left 左侧集合
* @param right 右侧集合
* @param comparator 元素比较器
* @param <T> 泛型
* @return 交集
*/
public static <T> List<T> remain(Collection<T> left, Collection<T> right, Comparator<T> comparator) {
Set<T> leftSet = new TreeSet<>(comparator);
leftSet.addAll(left);
return right.stream().filter(leftSet::contains).collect(Collectors.toList());
}