废话不多说直接上代码!
/**
* 获取两个数组相同元素
* @param a
* @param b
* @return
*/
public static <T> Set<T> getIds(T[] a, T[] b){
Set<T> same = new HashSet<T>(); //用来存放两个数组中相同的元素
Set<T> temp = new HashSet<T>(); //用来存放数组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 t1
* @param t2
* @return
*/
public static <T> List<T> compare(T[] t1, T[] t2) {
List<T> list1 = Arrays.asList(t1); //将t1数组转成list数组
List<T> list2 = new ArrayList<T>();//用来存放2个数组中不相同的元素
for (T t : t2) {
if (!list1.contains(t)) {
list2.add(t);
}
}
return list2;
}
/**
* 获取 两个数组不重复的元素值
* @param array1
* @param array2
* @return
*/
public static <T> List<T> getArrOnlyValue(T[] array1, T[] array2) {
List<T> R_arr = new ArrayList<T>();
Set<T> sameElementSet = getIds(array1,array2);
for(T i : sameElementSet) {
R_arr.add(i);
}
List<T> list = compare(array1,array2);
for (int i = 0; i < array2.length; i++) {
R_arr.add(list.get(i));
}
return R_arr;
}
public static void main(String[] arg){
String[] array1 = {"1","2","3","4","1","2","4","6","7","8","10","22","33"};
String[] array2 = {"1","2","3","4","1","2","4","6","7","8","10","22","33","55","66","77","88","99"};
Set<String> sameElementSet = getIds(array1,array2);
List<String> arr = new ArrayList<String>();
for(String i : sameElementSet) {
arr.add(i);
System.out.println(i);
}
System.out.println("----------------------------");
List<String> list = compare(array1,array2);
for (String str : list) {
arr.add(str);
//System.out.println(str);
}
for (String str : arr) {
System.out.print(str+"\t");
}
}
原文地址:https://www.cnblogs.com/userzf/p/10742123.html
时间: 2024-11-08 11:19:13