Merge Two Array In Java

 package demo;


import java.util.Arrays;

import java.util.stream.Stream;


public class MergeTwoArray {

public static void main(String[] args) {

Integer arr1[] = { 1, 3, 4, 5, 6, 7 };

Integer arr2[] = { 9, 12, 14, 16 };


Integer arr3[] = new Integer[arr1.length + arr2.length];

/* in java7 */


int pos = 0;

for (int i : arr1) {

arr3[pos] = i;

pos++;


}

for (int j : arr2) {

arr3[pos] = j;

pos++;

}


/* in java8 */

System.out.println(Arrays.toString(mergeArray(arr1, arr2)));


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


}


// function to merge two arrays

public static <T> Object[] mergeArray(T[] arr1, T[] arr2) {

return Stream.of(arr1, arr2).flatMap(Stream::of).toArray();

}


}


Comments

Popular posts from this blog

3 Lines of Code And You Can Download Your Favourite Youtube Video.

Leetcode Problem(Easy) Roman to Integer

Leetcode : (Find Minimum in Rotated Sorted Array)