java-ArrayList根据某个属性去重

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Student
{
private String sno;

private String name;

private int sex;

public Student(String sno, String name, int sex)
{
this.sno = sno;
this.name = name;
this.sex = sex;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getSno()
{
return sno;
}

public void setSno(String sno)
{
this.sno = sno;
}

public int getSex()
{
return sex;
}

public void setSex(int sex)
{
this.sex = sex;
}

@Override
public String toString()
{
return "Student [name=" + name + ", sno=" + sno + ", sex=" + sex + "]";
}

}

根据sno字段去重

1
2
3
4
5
6
7
8
9
10
11
List<Student> list = new ArrayList<Student>();

for (int i = 0; i < 3; i++)
{
list.add(new Student("123", "name", i));
}

list = list.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getSno))),
ArrayList::new));