在Java中,有多种方法可以实现数组去重。以下是几种常用的方法:
1. 使用Set:可以使用Set集合来去除重复元素。Set集合中不允许重复元素的存在,所以将数组中的元素添加到Set集合中,自动去除重复元素。
int[] arr = {1, 2, 3, 3, 4, 5, 5}; Setset = new HashSet<>(); for (int num : arr) { set.add(num); } // 遍历Set集合即可得到去重后的数组 int[] result = new int[set.size()]; int index = 0; for (int num : set) { result[index++] = num; }
2. 使用List:将数组中的元素添加到List集合中,再使用List的distinct()方法或者使用Stream的distinct()方法进行去重。
int[] arr = {1, 2, 3, 3, 4, 5, 5}; Listlist = new ArrayList<>(); for (int num : arr) { list.add(num); } // 使用distinct()方法进行去重 List distinctList = list.stream().distinct().collect(Collectors.toList()); // 将List集合转换为数组 int[] result = new int[distinctList.size()]; for (int i = 0; i < distinctList.size(); i++) { result[i] = distinctList.get(i); }
3. 使用数组排序:先对数组进行排序,然后遍历数组过滤重复元素。
int[] arr = {1, 2, 3, 3, 4, 5, 5}; Arrays.sort(arr); int n = arr.length; int count = 0; for (int i = 0; i < n; i++) { if (i == 0 || arr[i] != arr[i - 1]) { count++; } } int[] result = new int[count]; int index = 0; for (int i = 0; i < n; i++) { if (i == 0 || arr[i] != arr[i - 1]) { result[index++] = arr[i]; } }
以上是几种常见的Java数组去重方法,选择适合你的场景和需求的方法进行使用。
版权申明:财旺号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 1790309299@qq.com 举报,一经查实,本站将立刻删除。