在Java中,去重数组和集合的方法有多种,以下是一些常见的方法:
数组去重
使用Set集合
将数组素添加到Set集合中,Set集合不允许重复素,因此重复素会被自动过滤掉。
Setset = new HashSet<>(Arrays.asList(array)); int[] distinctArray = set.stream().mapToInt(Integer::intValue).toArray();
使用HashMap
遍历数组中的每个素,将素作为key存储到HashMap中,由于HashMap不允许重复的key,所以重复的素会被自动过滤掉。
Mapmap = new HashMap<>(); for (int num : array) {map.put(num, 1);}int[] distinctArray = map.keySet().stream().mapToInt(Integer::intValue).toArray();
使用Stream API
使用Java 8引入的Stream API,将数组转换为Stream,然后使用`distinct()`方法去重。
int[] distinctArray = Arrays.stream(array).distinct().toArray();
使用双重循环
遍历数组中的每个素,再嵌套一个循环,判断后面的素是否与当前素相同,如果相同则将后面的素删除。
int[] distinctArray = new int[array.length];int j = 0;for (int i = 0; i < array.length; i++) {boolean isDuplicate = false;for (int k = i + 1; k < array.length; k++) {if (array[i] == array[k]) {isDuplicate = true;break;}}if (!isDuplicate) {distinctArray[j++] = array[i];}}
使用Arrays.sort()方法
先对数组进行排序,然后遍历数组,判断相邻的素是否相等,如果相等则将后面的素删除。
Arrays.sort(array);int[] distinctArray = new int[array.length];int j = 0;for (int i = 0; i < array.length - 1; i++) {if (array[i] != array[i + 1]) {distinctArray[j++] = array[i];}}distinctArray[j] = array[array.length - 1];
集合去重
使用HashSet
HashSet是一种无序不重复集合,在添加素时会自动去重。
Setset = new HashSet<>(Arrays.asList(array)); int[] distinctArray = set.stream().mapToInt(Integer::intValue).toArray();
使用LinkedHashSet
LinkedHashSet是一种有序不重复集合,它会按照素的插入顺序进行排序。
Setset = new LinkedHashSet<>(Arrays.asList(array)); int[] distinctArray = set.stream().mapToInt(Integer::intValue).toArray();
使用ArrayList
ArrayList具有不允许重复素的特性,可以将数组中的素添加到ArrayList中,最后将ArrayList转换为数组。
Listlist = new ArrayList<>(Arrays.asList(array)); list.removeIf(x -> Collections.frequency(list, x) > 1);int[] distinctArray = list.stream().mapToInt(Integer::intValue).toArray();
使用Iterator的remove方法
通过Iterator遍历集合,利用其remove方法删除重复素。
Listlist = new ArrayList<>(Arrays.asList(array)); Iteratoriterator = list.iterator(); while (iterator.hasNext()) {Integer item = iterator.next();if (Collections.frequency(list, item) > 1) {iterator.remove();}}int[] distinctArray = list.stream().mapToInt(Integer::intValue).toArray();
以上方法均可根据具体需求选择使用。需要注意的是,使用集合去重时,集合的大小和性能会受到数据量和数据特性的影响。如果需要保留原始数组的顺序,可以使用LinkedHashSet;如果对性能有较高要求,可以考虑使用HashSet。使用Stream API进行去重通常是最简洁和灵活的方式
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/25900.html