ArrayList数据去重的方法
生活随笔
收集整理的這篇文章主要介紹了
ArrayList数据去重的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.使用LinkedHashSet刪除arraylist中的重復數據
-
LinkedHashSet是在一個ArrayList刪除重復數據的最佳方法。
-
LinkedHashSet在內部完成兩件事:
1 刪除重復數據2 保持添加到其中的數據的順序
輸出結果
[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8]Java示例使用LinkedHashSet刪除arraylist中的重復項。在給定的示例中,numbersList是包含整數的arraylist,其中一些是重復的數字。
例如1,3和5.我們將列表添加到LinkedHashSet,然后將內容返回到列表中。結果arraylist沒有重復的整數。
2.使用java8新特性stream進行List去重
要從arraylist中刪除重復項,我們也可以使用java 8 stream api。使用steam的distinct()方法返回一個由不同數據組成的流,通過對象的equals()方法進行比較。
收集所有區域數據List使用Collectors.toList()。
Java程序,用于在不使用Set的情況下從java中的arraylist中刪除重復項。
輸出結果
[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8]3.利用HashSet不能添加重復數據的特性 由于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方法循環遍歷,重新排序,只添加一次數據,避免重復:
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循環去重
for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size(); j++) { if(i!=j&&list.get(i)==list.get(j)) { list.remove(list.get(j)); } } }總結
以上是生活随笔為你收集整理的ArrayList数据去重的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 钉钉这次「下跪求饶」实在是高高高高高高明
- 下一篇: 测试显卡用什么软件最好,用什么软件能检测