要找出一个List中的重复数据,你可以使用两种方法:
方法一:使用两个循环来比较每个元素是否重复。
Listlist = Arrays.asList(1, 2, 3, 4, 1, 2, 3); List duplicates = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i).equals(list.get(j))) { duplicates.add(list.get(i)); } } } System.out.println(duplicates); // 输出 [1, 2, 3]
方法二:使用HashMap来统计元素出现的次数,然后找出出现次数大于1的元素。
Listlist = Arrays.asList(1, 2, 3, 4, 1, 2, 3); Map countMap = new HashMap<>(); List duplicates = new ArrayList<>(); for (int num : list) { if (countMap.containsKey(num)) { countMap.put(num, countMap.get(num) + 1); } else { countMap.put(num, 1); } } for (Map.Entry entry : countMap.entrySet()) { if (entry.getValue() > 1) { duplicates.add(entry.getKey()); } } System.out.println(duplicates); // 输出 [1, 2, 3]
这两种方法都可以找出List中的重复数据,你可以根据实际情况选择使用哪种方法。