java List去掉重復(fù)元素的幾種方式(小結(jié))
使用LinkedHashSet刪除arraylist中的重復(fù)數(shù)據(jù)(有序)
LinkedHashSet是在一個(gè)ArrayList刪除重復(fù)數(shù)據(jù)的最佳方法。LinkedHashSet在內(nèi)部完成兩件事:
刪除重復(fù)數(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集合中重復(fù)的元素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進(jìn)行List去重
要從arraylist中刪除重復(fù)項(xiàng),我們也可以使用java 8 stream api。使用steam的distinct()方法返回一個(gè)由不同數(shù)據(jù)組成的流,通過對象的equals()方法進(jìn)行比較。
收集所有區(qū)域數(shù)據(jù)List使用Collectors.toList()。
Java程序,用于在不使用Set的情況下從java中的arraylist中刪除重復(fù)項(xiàng)。
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); } }
注:當(dāng)數(shù)據(jù)元素是實(shí)體類時(shí),需要額外重寫equals()和hashCode()方法。例如:
以學(xué)號為依據(jù)判斷重復(fù)
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 +’}’; }}
到此這篇關(guān)于java List去掉重復(fù)元素的幾種方式(小結(jié))的文章就介紹到這了,更多相關(guān)java List去掉重復(fù)元素內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python自動化調(diào)用百度api解決驗(yàn)證碼2. 解決Android Studio 格式化 Format代碼快捷鍵問題3. Java Bean與Map之間相互轉(zhuǎn)化的實(shí)現(xiàn)方法4. vue實(shí)現(xiàn)web在線聊天功能5. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題6. SpringBoot+TestNG單元測試的實(shí)現(xiàn)7. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼8. Java使用Tesseract-Ocr識別數(shù)字9. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)10. Springboot 全局日期格式化處理的實(shí)現(xiàn)
