How to remove duplicate elements from an array in Java?
You can use a HashSet to remove duplicates from an array. HashSet is a collection that does not allow duplicate elements, so it’s easy to eliminate repeated elements from the array.
The following is an example code:
import java.util.Arrays;
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
// 使用HashSet去重
HashSet<Integer> set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
// 将HashSet转换为数组
int[] newArr = new int[set.size()];
int index = 0;
for (int num : set) {
newArr[index++] = num;
}
// 打印去重后的数组
System.out.println(Arrays.toString(newArr));
}
}
The code above first adds elements from an array to a HashSet, which automatically removes duplicates. Then it converts the elements in the HashSet back to an array, resulting in a deduplicated array.