1
public class MergeNames {
    public static void main(String[] args) {
        String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
        String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
        int na1 = names1.length;
        int na2 = names2.length;
        String [] result = new String[na1 + na2];
        System.arraycopy(names1, 0, result, 0, na1);
        System.arraycopy(names2, 0, result, na1, na2);
        System.out.println(Arrays.toString(result));
    }
}

I created Two Array Object String and Assign Same String values. After need to merge the two String array object into another String array Object.

Note: Without no duplication

I want output like ["Ava", "Emma", "Olivia", "Sophia", "Emma"]

2 Answers 2

1

You can use Java Stream API the Stream.of(). See the example for better understanding.

Reference Code

public class Main {
    public static <T> Object[] mergeArray(T[] arr1, T[] arr2)   
    {   
        return Stream.of(arr1, arr2).flatMap(Stream::of).distinct().toArray();   
    }   
    public static void main(String[] args) {
        String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
        String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
        
        Object [] result = mergeArray(names1, names2);
        
        System.out.println(Arrays.toString(result));
    }
}

Output

[Ava, Emma, Olivia, Sophia]
1

You have small mistake

String [] result = new String[na1 + na2];

not int

1
  • but need to remove duplication.
    – sudharsan
    Commented Jun 13, 2021 at 14:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.