Java 数组去重有两种常用方法:使用 HashSet 存储唯一元素,遍历 HashSet 获取去重数组;使用 Stream 和 distinct() 方法去除重复元素。

Java 数组去重
方法:
Java 中去重数组的方法有多种,其中最常用的有两种:
1. 使用 HashSet
立即学习“Java免费学习笔记(深入)”;
阿里云-虚拟数字人
阿里云-虚拟数字人是什么? …
2 查看详情
HashSet 是一种集合,它只存储唯一元素。我们可以将数组元素添加到 HashSet 中,然后遍历 HashSet 来获得去重后的数组。
import java.util.HashSet;import java.util.Arrays;public class ArrayDeduplication { public static void main(String[] args) { int[] nums = {1, 2, 2, 3, 4, 5, 5, 6, 7}; // 创建 HashSet,将数组元素添加到 HashSet 中 HashSet set = new HashSet(); for (int num : nums) { set.add(num); } // 遍历 HashSet 并将元素存储到新数组中 int[] deduplicatedNums = new int[set.size()]; int index = 0; for (int num : set) { deduplicatedNums[index++] = num; } // 打印去重后的数组 System.out.println(Arrays.toString(deduplicatedNums)); }}
2. 使用 Stream 和 distinct() 方法
Java 8 中的 Stream API 提供了 distinct() 方法,可以用来去除重复元素。
import java.util.Arrays;public class ArrayDeduplication { public static void main(String[] args) { int[] nums = {1, 2, 2, 3, 4, 5, 5, 6, 7}; // 创建 int 数组流 int[] deduplicatedNums = Arrays.stream(nums).distinct().toArray(); // 打印去重后的数组 System.out.println(Arrays.toString(deduplicatedNums)); }}
以上就是java数组怎么去重的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/367975.html
微信扫一扫
支付宝扫一扫