当前位置: 移动技术网 > IT编程>开发语言>Java > java List去掉重复元素的几种方式

java List去掉重复元素的几种方式

2020年03月13日  | 移动技术网IT编程  | 我要评论
使用LinkedHashSet删除arraylist中的重复数据(有序) 使用HashSet去重(无序) 使用java8新特性stream进行List去重 利用List的contains方法循环遍历 注:当数据元素是实体类时,需要额外重写equals()和hashCode()方法。 例如: 以学号为 ...

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网