java List去掉重復元素的幾種方式


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

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去重

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 +
                '}';
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM