在 Java 中去除数组中的重复元素可以通过以下两种常用方法:使用 Stream 和 Set:利用 Stream 转换数组为 Set 去重,再将其转换回数组。使用 HashSet:遍历数组,将元素添加到 HashSet 中以实现去重,再将其转换回数组。

如何去除 Java 数组中的重复元素
在 Java 中,去除数组中重复元素有多种方法。以下介绍最常用的两种方法:
1. 使用 Stream 和 Set
<code class="java">import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 1, 2, 3};
// 使用 Stream 和 Set
Set<Integer> uniqueElements = Arrays.stream(arr)
.boxed()
.collect(Collectors.toSet());
// 将 Set 转换回数组
int[] uniqueArray = uniqueElements.stream()
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(uniqueArray)); // 输出:"[1, 2, 3, 4, 5]"
}
}</code>2. 使用 HashSet
立即学习“Java免费学习笔记(深入)”;
<code class="java">import java.util.Arrays;
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 1, 2, 3};
// 使用 HashSet
HashSet<Integer> uniqueElements = new HashSet<>();
for (int element : arr) {
uniqueElements.add(element);
}
// 将 HashSet 转换回数组
int[] uniqueArray = new int[uniqueElements.size()];
int index = 0;
for (int element : uniqueElements) {
uniqueArray[index++] = element;
}
System.out.println(Arrays.toString(uniqueArray)); // 输出:"[1, 2, 3, 4, 5]"
}
}</code>以上就是java数组怎么去重复的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号