以下方法适用于java8之后的版本
List<Person> personList = new ArrayList<>();
personList.add(new Person("one", 20)); //Person(name,age)
personList.add(new Person("two", 10));
personList.add(new Person("three", 45));
//这两的name值重复
personList.add(new Person("four", 40));
personList.add(new Person("four", 78));
List<Person> personList2 = new ArrayList<>();
System.out.println("利用Collectors.toMap去重:");
//利用Collectors.toMap去重
personList.stream()
.collect(Collectors.toMap(Person::getName, Function.identity(), (oldValue, newValue) -> oldValue))
.values()
.stream()
.forEach(personList2::add); //最后将去重后的list数据一个一个的放到personList2中
Collections.sort(personList2)//java.util.Collections
//按照某个字段排序
//第一步:重写Person中的compareTo方法
@Override
public int compareTo(Person entity){
if(this.getAge() < entity.getAge()){
return 1;
}else{
return -1;
}
}
//第二步:直接使用
Collections.sort(personList2)
打印一下personList2得到以下结果
利用Collectors.toMap去重:
Person{name='two', age=10}
Person{name='one', age=20}
Person{name='four', age=40}
Person{name='three', age=45}