您好,登錄后才能下訂單哦!
利用java怎么去除List中的重復(fù)數(shù)據(jù)?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
前言
List 是一個(gè)接口,它繼承于Collection的接口。它代表著有序的隊(duì)列。當(dāng)我們討論List的時(shí)候,一般都和Set作比較。
List中元素可以重復(fù),并且是有序的(這里的有序指的是按照放入的順序進(jìn)行存儲(chǔ)。如按照順序把1,2,3存入List,那么,從List中遍歷出來(lái)的順序也是1,2,3)。
Set中的元素不可以重復(fù),并且是無(wú)序的(從set中遍歷出來(lái)的數(shù)據(jù)和放入順序沒(méi)有關(guān)系)。
以下介紹五種-不同的方法去除 Java 中ArrayList中的重復(fù)數(shù)據(jù)
1.使用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]
2.使用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); }
輸出結(jié)果
[1, 2, 3, 4, 5, 6, 7, 8]
3.利用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); }
4.利用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); }
5.雙重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--; } } } }
看完上述內(nèi)容,你們掌握利用java怎么去除List中的重復(fù)數(shù)據(jù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。