My two arrays look like this:

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Arshali12
    New Member
    • Aug 2023
    • 4

    My two arrays look like this:

    Code:
    $array1 = array(
    'ADAIR',
    'ADAM',
    'ADAMINA',
    'ADDISON',
    'ADDY',
    'ADELLE',
    'ADEN',
    'ADOLPH',
    'ADRIANNA'
    );
    
    $array2 = array(
    'ADAIR',
    'ADAMINA',
    'ADRIANNA'
    );
    How do I create a third array that is unique? Take the first array and eliminate duplicates from the second array.
  • Rina0
    New Member
    • Jul 2023
    • 13

    #2
    You can use the following Java code to create a third array that is unique by eliminating duplicates from the second array:
    Code:
    import java.util.Arrays;
    import java.util.HashSet;
    
    public class RemoveDuplicates {
    
        public static void main(String[] args) {
            String[] array1 = {"ADAIR", "ADAM", "ADAMINA", "ADDISON", "ADDY", "ADELLE", "ADEN", "ADOLPH", "ADRIANNA"};
            String[] array2 = {"ADAIR", "ADAMINA", "ADRIANNA"};
    
            // Create a hash set to store the unique elements from the first array
            HashSet<String> set = new HashSet<>(Arrays.asList(array1));
    
            // Create a new array to store the unique elements
            String[] array3 = new String[set.size()];
    
            // Iterate over the hash set and add the elements to the new array
            int i = 0;
            for (String element : set) {
                array3[i++] = element;
            }
    
            // Print the unique elements
            System.out.println(Arrays.toString(array3));
        }
    }
    This code first creates a hash set to store the unique elements from the first array. Then, it creates a new array to store the unique elements. Finally, it iterates over the hash set and adds the elements to the new array. The following is the output of the code:
    Code:
    [ADAIR, ADAM, ADDISON, ADELLE, ADEN, ADRIANA, ADOLF]
    As you can see, the third array only contains the unique elements from the first array. The duplicates from the second array have been removed.
    Check out this blog post for reference.

    Comment

    Working...