java List去掉重復元素的幾種方式(小結)
使用LinkedHashSet刪除arraylist中的重復數(shù)據(jù)(有序)
LinkedHashSet是在一個ArrayList刪除重復數(shù)據(jù)的最佳方法。LinkedHashSet在內(nèi)部完成兩件事:
刪除重復數(shù)據(jù) 保持添加到其中的數(shù)據(jù)的順序List<String> words= Arrays.asList('a','b','b','c','c','d');HashSet<String> set=new LinkedHashSet<>(words);for(String word:set){ System.out.println(word);}
使用HashSet去重(無序)
//去掉List集合中重復的元素List<String> words= Arrays.asList('a','b','b','c','c','d');//方案一:for(String word:words){ set.add(word);}for(String word:set){ System.out.println(word);}
使用java8新特性stream進行List去重
要從arraylist中刪除重復項,我們也可以使用java 8 stream api。使用steam的distinct()方法返回一個由不同數(shù)據(jù)組成的流,通過對象的equals()方法進行比較。
收集所有區(qū)域數(shù)據(jù)List使用Collectors.toList()。
Java程序,用于在不使用Set的情況下從java中的arraylist中刪除重復項。
List<String> words= Arrays.asList('a','b','b','c','c','d');words.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);
利用List的contains方法循環(huán)遍歷
List<String> list= new ArrayList<>(); for (String s:words) { if (!list.contains(s)) {list.add(s); } }
注:當數(shù)據(jù)元素是實體類時,需要額外重寫equals()和hashCode()方法。例如:
以學號為依據(jù)判斷重復
public class Student { String id; String name; int age; public Student(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(id, student.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } @Override public String toString() { return 'Student{' +'id=’' + id + ’’’ +', name=’' + name + ’’’ +', age=' + age +’}’; }}
到此這篇關于java List去掉重復元素的幾種方式(小結)的文章就介紹到這了,更多相關java List去掉重復元素內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. 用xslt+css讓RSS顯示的跟網(wǎng)頁一樣漂亮2. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉換成文字3. 《CSS3實戰(zhàn)》筆記--漸變設計(一)4. 測試模式 - XSL教程 - 55. Ajax實現(xiàn)異步加載數(shù)據(jù)6. 教你JS更簡單的獲取表單中數(shù)據(jù)(formdata)7. ASP.NET Core自定義中間件的方式詳解8. html5手機觸屏touch事件介紹9. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效10. 讓chatgpt將html中的圖片轉為base64方法示例
