Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,866 questions

51,788 answers

573 users

How to find the uncommon elements from two arrays in Java

2 Answers

0 votes
public class MyClass {
    static void printUncommonElements(int arr1[], int arr2[]) {
        int i = 0, j = 0;
        int len1 = arr1.length, len2 = arr2.length; 

        while(i < len1 && j < len2) {
          if(arr1[i] < arr2[j])
             System.out.println(arr1[i++]);
          else if (arr1[i] > arr2[j]) 
             System.out.println(arr2[j++]);
          else { 
             i++;
             j++;
          }
        }
        while(i < len1 && arr1[i] != arr2[j])
          System.out.println(arr1[i++]);
        i--;  
        while(j < len2 && arr2[j] != arr1[i]) 
          System.out.println(arr2[j++]);
    }
    public static void main(String args[]) {
        int arr1[]= {1, 3, 8,  9, 17, 18};
        int arr2[]= {1, 8, 5, 12, 18, 19, 100, 120};

        printUncommonElements(arr1, arr2);
    }
}



/*
run:

3
5
9
12
17
19
100
120

*/

 



answered Jul 20, 2020 by avibootz
edited Jul 20, 2020 by avibootz
0 votes
import java.util.*; 
import java.util.stream.Collectors;

public class MyClass {
    static void printUncommonElements(int arr1[], int arr2[]) {
        List<Integer> list1 =  Arrays.stream(arr1).boxed().collect(Collectors.toList());
        List<Integer> list2 = Arrays.stream(arr2).boxed().collect(Collectors.toList());

        Set<Integer> hs = new HashSet<Integer>(list1);
        hs.addAll(list2);
        Set<Integer> intersection = new HashSet<Integer>(list1);
        intersection.retainAll(list2);
        hs.removeAll(intersection);
        for (Integer n : hs) {
            System.out.println(n);
        }
    }
    public static void main(String args[]) {
        int arr1[]= {1, 3, 8, 9, 17, 18};
        int arr2[]= {1, 8, 5, 8, 12, 18, 19, 100, 120, 8};

        printUncommonElements(arr1, arr2);
    }
}



/*
run:

17
3
19
100
5
120
9
12

*/

 



answered Jul 20, 2020 by avibootz

Related questions

1 answer 94 views
1 answer 92 views
1 answer 90 views
1 answer 85 views
1 answer 94 views
1 answer 86 views
...