Learn how to Merging Two Unsorted Arrays in Sorted Order Using Java 8 with IntStream.concat(), distinct(), sorted(), and toArray() methods.
Code Explanation (Step-by-Step)
- Two unsorted arrays are created.
- Both arrays are converted into integer streams using Arrays.stream().
- IntStream.concat() merges both integer streams into single stream .
- distinct() removes duplicate values.
- sorted() method sorts the stream elements in ascending order.
- toArray() converts the stream back into an integer array.
- Arrays.toString(sortedArray) converts the array into a readable string format and prints the final sorted array.
import java.util.Arrays;
import java.util.stream.IntStream;
public class MergeTwoUnsortedArray {
public static void main(String[] args) {
int[] a = {3, 6, 8, 10, 10};
int[] b = {20, 15, 5};
int[] sortedArray = IntStream.concat(Arrays.stream(a), Arrays.stream(b))
.distinct()
.sorted()
.toArray();
System.out.println("Merging two unsorted arrays: " + Arrays.toString(sortedArray));
}
}
Output :
Merging two unsorted arrays: [3, 5, 6, 8, 10, 15, 20]
Use Cases of Java 8 distinct() Method :
Removing Duplicate User Records
Remove duplicate email IDs before processing login or notifications.
Eliminating Duplicate Entries from API Response
API responses sometimes return repeated data due to backend joins.so clean the response data before sending it to UI.
Data Cleaning Before Database Insert
To avoid constraint violations (like unique keys), duplicates must be removed.
Removing Duplicate Objects (Custom Classes)
Works with objects using equals() and hashCode() methods. likes Filter unique employees, products, etc.
list.stream()
.distinct()
.collect(Collectors.toList());
Removing Duplicate Integers from Arrays
int[] arr = {1, 2, 2, 3, 4, 4};
IntStream.of(arr)
.distinct()
.forEach(System.out::println);
FAQ
How do you merge two unsorted arrays in Java 8?
You can merge two unsorted arrays in Java 8 by converting both arrays into streams using Arrays.stream() and then combining them using IntStream.concat().
How do you sort merged arrays in Java 8?
You can sort merged arrays in Java 8 by using the sorted() method after combining both arrays into a single stream.
How do you remove duplicate values while merging arrays in Java 8?
You can remove duplicate values by using the distinct() method in the stream pipeline.
Which Java 8 method is used to combine two integer streams?
The IntStream.concat() method is used to combine two integer streams into a single stream.