合并集合中重复的员工对象,并在Java 8中用逗号附加其部门名称

class Employee{
    Long id;
    String name;
    String department;

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof Employee)) {
            return false;
        }

        Employee emp = (Employee) o;
        return emp.id.equals(id);
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + name.hashCode();
        result = 31 * result + id;
        result = 31 * result + department.hashCode();
        return result;
    }
}    

    class Test {
         public static void main(String[] args){
            Employee e1 = new Employee(100, "Shailesh", "HR");
            Employee e2 = new Employee(100, "Shailesh", "IT");
            Employee e3 = new Employee(101, "Vikram", "HR");
            Set employees = new HashSet();
            employees.add(e1);
            employees.add(e2);
            employees.add(e3);
    //write logic to get unique employee list with department appended with comma
    }
    }

所需结果: 员工集应包含两个唯一的员工对象“ Shailesh”和“ Vikram”,但是由于“ Shailesh”对象是两倍 所以两个部门都应该附加逗号

经过处理的员工集应仅包含以下两个对象:

Employee e1 = new Employee(100, "Shailesh", "HR, IT");
Employee e3 = new Employee(101, "Vikram", "HR");
评论