List去除重復(fù)數(shù)據(jù)的五種方式
點(diǎn)擊上方 Java學(xué)習(xí)之道,選擇 設(shè)為星標(biāo)
來(lái)源: blog.csdn.net/qq_37939251/article/details/90713643l
作者: 多纖果凍
Part1使用LinkedHashSet刪除arraylist中的重復(fù)數(shù)據(jù)
LinkedHashSet是在一個(gè)ArrayList刪除重復(fù)數(shù)據(jù)的最佳方法。LinkedHashSet在內(nèi)部完成兩件事:
-
刪除重復(fù)數(shù)據(jù) -
保持添加到其中的數(shù)據(jù)的順序
Java示例使用 LinkedHashSet 刪除 arraylist 中的重復(fù)項(xiàng)。在給定的示例中,numbersList是包含整數(shù)的 arraylist,其中一些是重復(fù)的數(shù)字,例如1,3和5.我們將列表添加到LinkedHashSet,然后將內(nèi)容返回到列表中。結(jié)果arraylist沒(méi)有重復(fù)的整數(shù)。
public static void main(String[] args) {
int List[] =[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(List);
ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
System.out.println(listWithoutDuplicates);
}
輸出結(jié)果
[1, 2, 3, 4, 5, 6, 7, 8]
Part2使用java8新特性stream進(jìn)行List去重
要從arraylist中刪除重復(fù)項(xiàng),我們也可以使用 java 8 stream api。使用 steam 的 distinct() 方法返回一個(gè)由不同數(shù)據(jù)組成的流,通過(guò)對(duì)象的 equals() 方法進(jìn)行比較。
收集所有區(qū)域數(shù)據(jù)List使用 Collectors.toList()。
Java程序,用于在不使用Set的情況下從java中的arraylist中刪除重復(fù)項(xiàng)。
public static void main(String[] args){
int List[] =[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
List<Integer> listWithoutDuplicates = List.
stream().
distinct().
collect(Collectors.toList());
System.out.println(listWithoutDuplicates);
}
Part3利用HashSet不能添加重復(fù)數(shù)據(jù)的特性
由于HashSet不能保證添加順序,所以只能作為判斷條件保證順序:
private static void removeDuplicate(List<String> list) {
HashSet<String> set = new HashSet<String>(list.size());
List<String> result = new ArrayList<String>(list.size());
for (String str : list) {
if (set.add(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
}
Part4利用List的contains方法循環(huán)遍歷,重新排序,只添加一次數(shù)據(jù),避免重復(fù)
private static void removeDuplicate(List<String> list) {
List<String> result = new ArrayList<String>(list.size());
for (String str : list) {
if (!result.contains(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
}
Part5雙重for循環(huán)去重
public static void main(String[] args) {
int List[] = [1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
for (int i = 0; i < List.size(); i++) {
for (int j = i + 1; j < List.size(); j++) {
if (List.get(i) == List.get(j)) {
List.remove(j);
j--;
}
}
}
}
-
| 更多精彩文章 -
![]()
▽加我微信,交個(gè)朋友 長(zhǎng)按/掃碼添加↑↑↑

評(píng)論
圖片
表情

