JAVA两个数组间元素的比较(找出相同或者不同元素)
JAVA两个数组间元素的比较(找出相同或者不同元素)
转载自 https://blog.csdn.net/qq_35792598/article/details/76149552
1,找出两个数组中相同的元素
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;   
  }  
  public static void main(String[] arg){  
        Integer[] array1 = {1,2,3,4,1,2,4,6,7,8,10,22,33};  
        Integer[] array2 = {1,2,3,4,1,2,4,6,7,8,10,22,33,55,66,77,88,99};  
        Set<Integer> sameElementSet = getIds(array1,array2);  
        for(Integer i : sameElementSet) {  
        System.out.println(i);  
        }   
  }  
输出:
1 
2 
33 
3 
4 
6 
22 
7 
8 
10
2,找出两个数组中不相同的元素
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;    
  }   
  public static void main(String[] arg){  
        Integer[] array1 = {1, 2, 3};  
        Integer[] array2 = {1, 2, 3, 4,44};  
        List<Integer> list = compare(array1,array2);  
        for (Integer integer : list) {  
            System.out.println(integer);  
        }  
  }  
输出:
4 
44
补充
比较2个数组不相同的元素, 应该遍历多的, 然后在遍历中拿少的跟多的比较。
for (T t : 多) {
if (!少.contains(t)) {
不相同的集合.add(t);
}
}
其中 :
多 为 多的集合
少 为 少的集合
t 为 多的集合的元素
不相同的集合 为 放不相同元素的集合
    此博客只是为了记忆相关知识点,大部分为网络上的文章,在此向各个文章的作者表示感谢!
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号