java——list<Employee>转set

  1. List 集合和Set 集合的区别
    (1) list 和 set 都继承了Collection。
    (2) list是有顺序的所以它的值是可以重复的
    (3)set 是无序的不能插入重复元素
  2. list转set注意事项:
    以下列测试代码为例
    员工类
public class Employee {
    private int id;
    private String name;
    private String department;
    private double money;
    public Employee(int id, String name, String department, double money) {
        this.id = id;
        this.name = name;
        this.department = department;
        this.money = money;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id== employee.id;
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    @Override
    public String toString() {
        return  "工号=" + id +
                ", 姓名='" + name + '\'' +
                ", 部门='" + department + '\'' +
                ", 工资=" + money ;
    }
}

测试代码:

public class MainClass {
    public static boolean isRepeat(List<Employee> list) {
        Set<Employee> set=new HashSet<>(list);
        if(list.size()!=set.size())
            return true;
        return false;
    }
    public static void main(String[] args) {
        List<Employee> list=new ArrayList<>();
        list.add(new Employee(10001,"小王","销售部",5000));
        list.add(new Employee(10002,"小赵","销售部",6500));
        list.add(new Employee(10001,"Alan","研发部",15000));
        List<Employee> EmployeeList = new ArrayList<>(new HashSet<>(list));//转换
        
        System.out.println("去重之前是否有重复工号:"+(isRepeat(list)?"有":"没有"));
        list.forEach(a->{
            System.out.println(a);
        });

        System.out.println("去重之后是否有重复工号:"+(isRepeat(EmployeeList)?"有":"没有"));
        EmployeeList.forEach(a->{
            System.out.println(a);
        });
    }
}

java——list<Employee>转set
这里去掉的是工号为10001的Alan,因为它与小王的工号重复了,为什么只根据工号去重?答案在Employee 里重写的equals和hashCode方法:

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id;
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

而关键在于equals里的return id == employee.id;和hashCode里的return Objects.hash(id);两句,亲测,这两个方法需要保持一致,不然不起效果,具体为什么,还等待我去深究。
同理,如果你想去掉重复部门,只需要把这两方法的id换成department ,如果需要去掉姓名和部门均一样的数据,只需要改成 return name==employee.name&&department ==employee.department 和return Objects.hash(name,department );

上一篇:MYSQLsql99语法内连接


下一篇:Mysql常用sql语句(12)- group by 分组查询