Reputation:
I was just wondering if it is possible to merge two arrays by sequence .
Do we have to use an normal array , arraylist or etc etc. Put it that we have 2 array variable
//Array 1 :
String[] Array_1 = {"a","b","c"}
String[] Array_2 = {"1","2","3"}
//Now we want to combine both of those array to one. The trick is, we have to do it in such
//sequence
//Outout
//Array_3 when combined should display in such manner = {"a","1","b","2","c","3"}
Thank you in advance :)
Upvotes: 0
Views: 129
Reputation: 56
This can be done by implementing your own method rather than using any built-in Standard Java Libraries.
If you think you will be constantly merging or reducing the data structure, then list would be the way to go as Lists can grown and shrink dynamically, else continue to use Arrays if its a one time thing.
public String[] merge(String[] arr1, String[] arr2) {
// note Array lengths can be different and the order in which we
// want the items to get added is important
int arr1Len = arr1.length;
int arr2Len = arr2.length;
// firstOrder denotes which array item should get printed first
// secondOrder denotes which array item should get printed next
if(arr1Len <= arr2Len) {
return copyArrayInSequence(arr1, arr2, 0, 1);
}
return copyArrayInSequence(arr2, arr1, 1, 0);
}
public String[] copyArrayInSequence(String[] smallArr, String[] bigArr, int firstOrder, int secondOrder) {
int smallLen = smallArr.length;
int bigLen = bigArr.length;
String[] mergedArr = new String[smallLen+bigLen];
for(int i=0; i<smallLen; i++) {
mergedArr[i*2 + firstOrder] = smallArr[i];
mergedArr[i*2 + secondOrder] = bigArr[i];
}
for(int i=smallLen; i<bigLen; i++) {
mergedArr[smallLen+i] = bigArr[i];
}
return mergedArr;
}
List Implementation is easier as we do not need to keep track of where we are and can dynamically add the individual strings.
Upvotes: 1
Reputation: 393866
Yes, you can iterate over the arrays, add their elements to a List
and convert that List
to an array.
Or you can do the same with streams:
String[] Array_3 =
IntStream.range(0,Array_1.length)
.boxed()
.flatMap(i -> Stream.of(Array_1[i],Array_2[i]))
.toArray(String[]::new);
System.out.println (Arrays.toString(Array_3));
Output:
[a, 1, b, 2, c, 3]
Upvotes: 4
Reputation: 59996
If all the arrays has the same length, and If you are using Java 8 you can use Streams like so :
String[] result = IntStream.range(0, array_1.length)
.mapToObj(index -> Stream.of(array_1, array_2)
.map(arr -> arr[index])
).flatMap(strm -> strm.collect(Collectors.toList()).stream())
.toArray(String[]::new);
Or :
List<String[]> arrays = Arrays.asList(array_1, array_2);
String[] strings = IntStream.range(0, array_1.length)
.mapToObj(index -> arrays.stream().map(arr -> arr[index])
).flatMap(strm -> strm.collect(Collectors.toList()).stream())
.toArray(String[]::new);
Outputs:
[a, 1, b, 2, c, 3]
Upvotes: 2