I have two sorted integer arrays. I am looking to merge them into one sorted array. I would like to use Java Stream to achieve this. Can I do nested stream?
Arrays.asList(nums1).stream()
.forEach(i -> Arrays.asList(nums2).stream()
.forEach(j -> //compare i,j)
.collect as list// ;
For example [1,3,4]
and [2,5]
should return [1,2,3,4,5]
CodePudding user response:
Java uses an implementation of the Timsort algorithm, which is good at spotting sorted chunks of data in the input, in order to sort an array of reference type (Arrays.asList()
that you've used in your example expects varargs T
, so I assume we are talking about objects).
Therefore, if we simply concatenate the two data sets it will still perform reasonably well.
String[] nums1 = {"1", "3", "4"};
String[] nums2 = {"2", "5"};
String[] merged = Stream.concat(Arrays.stream(nums1), Arrays.stream(nums2))
.sorted()
.toArray(String[]::new);
System.out.println(Arrays.toString(merged));
Output:
[1, 2, 3, 4, 5]
In case if you want to use conditional logic in order, then you must go with a plain for
loop. It's not a job for a stream.
CodePudding user response:
Streams are nice but i recommend you this way because with streams you first have to change the arrays to streams only to work on them which could get expensive
public static String[] mergeAndSort(String[] arr1, String[] arr2) {
int nums1Size = arr1.length;
int nums2Size = arr2.length;
String[] result = new String[nums1Size nums2Size];
System.arraycopy(arr1, 0, result, 0, nums1Size);
System.arraycopy(arr2, 0, result, nums1Size, nums2Size);
Arrays.sort(result);
return result;
}