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,885 questions

51,811 answers

573 users

How to implement a function that merge and sort two arrays without duplicates in Java

1 Answer

0 votes
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.IntStream;
import java.util.Iterator;

public class MyClass {
    private static int[] merge_arrays_sort_and_remove_duplicates(int[] arr1, int[] arr2) {
        int[] arr1_arr2 = new int[arr1.length + arr2.length];
         
        int i = 0, k = 0;
        while (i < arr1.length) {
            arr1_arr2[k] = arr1[i];
            k++;
            i++;
        }
        
        int j = 0; 
        while (j < arr2.length) {
            arr1_arr2[k] = arr2[j];
            k++;
            j++;
        }
         
        Set<Integer> set_no_duplicates = new HashSet<>();
         
        for (int idx = 0; idx < arr1_arr2.length; idx++) {
            set_no_duplicates.add(arr1_arr2[idx]);
        }
         
        Iterator<Integer> it = set_no_duplicates.iterator();
         
        int[] merged_array = new int[set_no_duplicates.size()];
         
        int n = 0;
         
        while (it.hasNext()) {
            merged_array[n] = it.next();
            n++;
        }
         
        Arrays.sort(merged_array);
         
        return merged_array;
    }
    public static void main(String args[]) {
        int[] arr1 = new int[] {1, 2, 1, 7, 1, 3, 5, 6};
        int[] arr2 = new int[] {1, 6, 4, 2, 2, 8, 9, 8, 0};
         
        int[] merged_array = merge_arrays_sort_and_remove_duplicates(arr1, arr2);

        System.out.println(Arrays.toString(merged_array));
    }
}



/*
run:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

*/

 



answered Nov 24, 2019 by avibootz

Related questions

1 answer 189 views
1 answer 123 views
2 answers 139 views
2 answers 103 views
1 answer 185 views
1 answer 126 views
1 answer 116 views
...