Write a Java program to remove duplicates from an array.
This Java program efficiently removes duplicate elements from an array using the Arrays.stream() and distinct() methods, which are part of the Java Streams API introduced in Java 8. Here’s an explanation of how it works:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr = {3, 3, 6, 7, 8, 9, 9};
int[] result = removeDuplicate(arr);
System.out.print("After remove duplicate array is: " + Arrays.toString(result));
}
public static int[] removeDuplicate(int[] arr) {
return Arrays.stream(arr).distinct().toArray();
}
}
Output:
After remove duplicate array is: [3, 6, 7, 8, 9]
How It Works
- Input Array:
- The input array, arr, is {3, 3, 6, 7, 8, 9, 9}.
- Stream Conversion:
- Arrays.stream(arr) converts the array to a stream, enabling functional-style operations.
- Removing Duplicates:
- The .distinct() method ensures only unique elements remain in the stream.
- Conversion Back to Array:
- .toArray() collects the unique elements into a new array.
- Output:
- The result is an array with duplicates removed.
Advantages
- Simplicity:
- The code is concise and leverages Java’s Streams API to handle duplicates efficiently.
- Performance:
- The .distinct() method uses hashing internally, providing good performance for moderately sized arrays.
- Readability:
- Functional-style programming makes the logic straightforward and readable.
Edge Cases
- Empty Array:
- Input: arr = {}
- Output: After remove duplicate array is: []
- Array Without Duplicates:
- Input: arr = {1, 2, 3}
- Output: After remove duplicate array is: [1, 2, 3]
- All Elements Are Duplicates:
- Input: arr = {5, 5, 5}
- Output: After remove duplicate array is: [5]
- Negative Numbers and Zero:
- Input: arr = {-1, 0, -1, 0, 1}
- Output: After remove duplicate array is: [-1, 0, 1]
Limitations
- For extremely large arrays, memory usage could be a concern since a stream pipeline is created.