共計(jì) 802 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
要找出一個(gè) List 中的重復(fù)數(shù)據(jù),你可以使用兩種方法:
方法一:使用兩個(gè)循環(huán)來(lái)比較每個(gè)元素是否重復(fù)。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2, 3);
List<Integer> 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 來(lái)統(tǒng)計(jì)元素出現(xiàn)的次數(shù),然后找出出現(xiàn)次數(shù)大于 1 的元素。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2, 3);
Map<Integer, Integer> countMap = new HashMap<>();
List<Integer> 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<Integer, Integer> entry : countMap.entrySet()) {if (entry.getValue() > 1) {duplicates.add(entry.getKey());
}
}
System.out.println(duplicates); // 輸出 [1, 2, 3]
這兩種方法都可以找出 List 中的重復(fù)數(shù)據(jù),你可以根據(jù)實(shí)際情況選擇使用哪種方法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完