您的位置:首頁技術文章
文章詳情頁

java List去掉重復元素的幾種方式(小結)

瀏覽:3日期:2022-08-31 11:20:19

使用LinkedHashSet刪除arraylist中的重復數據(有序)

LinkedHashSet是在一個ArrayList刪除重復數據的最佳方法。LinkedHashSet在內部完成兩件事:

刪除重復數據 保持添加到其中的數據的順序

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()方法返回一個由不同數據組成的流,通過對象的equals()方法進行比較。

收集所有區域數據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方法循環遍歷

List<String> list= new ArrayList<>(); for (String s:words) { if (!list.contains(s)) {list.add(s); } }

注:當數據元素是實體類時,需要額外重寫equals()和hashCode()方法。例如:

以學號為依據判斷重復

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去掉重復元素內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章:
国产综合久久一区二区三区