Home > Back-end >  merge two arrays ,remove duplicates and sort into ascending order
merge two arrays ,remove duplicates and sort into ascending order

Time:06-22

I am trying to merge two arrays, remove duplicates and arrange in ascending order. Whenever I am trying to do this it's showing wrong.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
            
            
class Main {
            
    public static void main(String[] args) {
        int a[] = { 1, 2, 3, 4 };
        int b[] = { 1, 2, 3, 4, 5 };
                        
        HashMap<Integer, Integer> h1 = new HashMap<>();
                        
        for (int i = 0; i < a.length; i  )
            h1.put(a[i], i);
                        
            for (int i = 0; i < b.length; i  )
                h1.put(b[i], i);
                        
                for (Map.Entry<Integer, Integer> m1 : h1.entrySet())
                    System.out.print(m1.getKey()   " ");
                    System.out.println();
                }
            }
        }
    }
}

CodePudding user response:

You can use TreeSet. It automatically removes duplicates and sort itself in ascending order:

int[] a = { 1, 2, 3, 4 };
int[] b = { 1, 2, 3, 4, 5 };

TreeSet<Integer> ts = new TreeSet<>();

for(int j : a) {
    ts.add(j);
}
for(int j : b) {
    ts.add(j);
}

System.out.println(ts);

The output will be: [1, 2, 3, 4, 5]

You can read more about TreeSets here.

CodePudding user response:

First try to fix the curly brackets (they should match). The code should work but it can be optimized by using a HashSet instead of a HashMap

CodePudding user response:

The solution mentioned in comments with TreeSets is ideal, but if you wanted to do it the old-school way, see below for a rough working idea, although there is a lot that could be improved upon:

public static void main(String[] args) throws IOException, InterruptedException
{
    int a[] = { 1, 3, 7, 4, 2 };
    int b[] = { 1, 2, 3, 4, 5 };

    //Add all items to the array using a helper method
    //A better solution is shown here: https://stackoverflow.com/questions/8938235/sort-an-array-in-java
    for (int i : b){
        a = addToArray(a, i);
    }

    //Remove duplicates using a helper method
    //Ideally you would check duplicates before adding them to the array
    a = removeDuplicates(a);
    
    //Sort in ascending order
    Arrays.sort(a);
    
    System.out.println(Arrays.toString(a));
}

//Add one item to an array at a time
public static int[] addToArray(int[] array, int newItem){
    //create a new array that is 1 larger
    int[] newArray = new int[array.length   1];
    //copy the array
    System.arraycopy(array, 0, newArray, 0, array.length);
    //Add the new element to the end
    newArray[array.length] = newItem;
    //return the new array
    return newArray;
}

public static int[] removeDuplicates(int[] array){
    int[] newArray = new int[0];
    
    //Iterate the array and check for duplicates
    for (int i : array){
        //Use a flag to track duplicates
        boolean duplicate = false;
        for (int j : newArray){
            if(i == j){
                //break when a duplicate is found and set the flag
                duplicate = true;
                break;
            }
        }

        //Only add the item to the new array if it's not a duplicate
        if(duplicate == false){
            newArray = addToArray(newArray, i);
        }
    }

    //Return the new array
    return newArray;
}

And the result of the main method output is:

[1, 2, 3, 4, 5, 7]

CodePudding user response:

You're having troubles with your code because you're not properly merging the two arrays. In fact, there are a couple of errors in your code.

First of all, you're nesting the addition of the two arrays' elements within the HashMap. I think, you might want to place that second for outside the first one or else you will add b's elements in the HashMap a.length times.

Secondly, you don't need a HashMap to uniquely store your elements, I understand that you want to take advantage of the fact that a Map cannot have multiple equal keys, but you could simplify that by employing a Set, specifically a TreeSet to keep unique elements and maintain the ascending order. In fact, you don't need to store pairs (a key and a value), but just values.

Your original code could be fixed like this:

int a[] = {1, 2, 3, 4};
int b[] = {1, 2, 3, 4, 5};

//Set instantiated with a TreeSet to maintain the natural order of its elements (ascending) and to maintain only unique elements
Set<Integer> set = new TreeSet<>();

//Adding the elements of a within the Set with an enhanced for (or for-loop)
for (int i : a) {
    set.add(i);
}

//Adding the elements of b within the Set with an enhanced for (or for-loop)
for (int j : b) {
    set.add(j);
}

//Printing the Set's content on screen
System.out.println(set);

Alternatively, you could achieve the same result with a more compact syntax by using streams.

int a[] = {1, 2, 3, 4};
int b[] = {1, 2, 3, 4, 5};

int c[] = Stream.concat(Arrays.stream(a).boxed(), Arrays.stream(b).boxed())  //concatenating the elements from a and b seen as Integer rather than int
        .distinct()  //keeping only distinct elements
        .sorted()    //sorting the elements according to their natural ordering (scending)
        .mapToInt(Integer::intValue)  //Mapping each Integer to their primitive type (int)
        .toArray();  //Collecting the remaining elements into an array of int[]

System.out.println(Arrays.toString(c));

Output

[1, 2, 3, 4, 5]
  • Related