JAVA PROGRAM TO MERGE TO ARRAYS

 

Two  arrays  are   given.  Merge  them  into  one   Array.

 

Example  :

 

 Input  Array1:  int[]  arr1= { 13, 17,  88,  93,  65};

  Input  Array2:  int[]   arr2= { 35, 45, 68};

 

  Output:

       [13, 17 , 88 ,  93 ,  65 , 35 ,  45 ,  68 ]

     

    

 

 

 

Approach1 :  Without  using  pre-defined  function 

 

 

 

import  java.util.Arrays;

 

public  class  MergeArray {

       public  static  void  main  (String  args[] ) {

           int   arr1[]  =   { 29, 35,  37,43,67};

           int   arr2[] = { 65, 75,88};

        

//Determining  the  length  of  both  arrays

 

      int    a1 =  arr1.length;

      int  a2 = arr2.length;

     

//Size  of  the  resultant array

     int     c1 =  a1 + b1;

    // Creating  a  new  array          

       int   c[ ]  = new   int[c1];

 

     //Loop  to  store  the  elements  of  first  array  into  resultant  array

     for( int  i=0 ; i<a1 ; i++ ) {

               c [ i ]= arr1[i];

      }

   //Loop  to  concat  the  elements  of  second  array  into  the  resultant  array  to  merge

 

    for ( int  i=0 , i<b1 ; i++ ) {

          c[a1+i] = arr2[i] ;

      }

 

System.out.println(“Merged  array is :”+Arrays.toString(c));

     }

  }

 

 

 

 

 

 

 

OUTPUT :

 

[29 ,35 , 37 , 43 , 67 , 65 , 75 , 88 ]

 

 

 

Approach 2 :  Using  Java  Streams

 

 

 import   java.util.Arrays;

 import   java.util.stream.IntStream;

 

  public  class    MergeArray{

 

 //  Method  to  merge  two  arrays  using  Java  Streams

 

         public   static   int [ ]   mergeArrayWithStreams( int [ ]  arr1 ,  int [ ]   arr2 ) {

              return     IntStream.concat(Arrays.stream(arr1) , Arrays.stream(arr2)).toArray( ) ;

       }

     

  public  static  void  main (String  args [] ) {

       int   arr1 [ ] = { 35 , 39 , 45, 47 , 55};

       int   arr2 [ ] = { 65 , 75 , 88 };

 

 

     // Merging  arrays  using  Java  Streams   by  calling  the  above  method  mergeArrayWithStreams(int arr1[] , int  arr2[]) .

 

        int     mergedArr [] =  mergeArrayWithStreams( arr1 , arr2 ) ;

       System.out.println(“Merged array  is :”+Arrays.toString(mergedArr));

      }

 

   }

 

 

 

     

  

 

 

OUTPUT :

 

 

[ 35 , 39 , 45 , 47 , 55 ,  65 , 75 , 88 ]

 

Leave a Comment

Your email address will not be published. Required fields are marked *