java的list的几种排序写法整理(sort的用法)
版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/heliangb46/article/details/77188939
java的实体bean结构
importjava.util.ArrayList;
importjava.util.List;
publicclassHuman{
privateString name;
privateintage;
publicHuman(){
}
publicHuman(String name,intage){
this.name = name;
this.age = age;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(String name){
this.name = name;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age = age;
}
@SuppressWarnings("serial")
publicstaticListgetAInitHumanList(){
returnnewArrayList() {
{
add(newHuman("guorao",10));
add(newHuman("mako",12));
add(newHuman("hel",30));
add(newHuman("lin",28));
}
};
}
@Override
publicStringtoString(){
returnthis.getName() +":"+this.getAge();
}
}
第一种:实现Comparator接口的类的对象作为sort的入参
publicclassHumanComparetorimplementsComparator{
@Override
publicintcompare(Human h1, Human h2){
if(h1.getAge() > h2.getAge()) {
return1;
}elseif(h1.getAge() == h2.getAge()) {
return0;
}else{
return-1;
}
}
}
publicstaticvoidmain(String[] args){
List
Collections.sort(humans,newHumanComparetor());
System.out.println(humans);
}
第二种:在方法的局部使用局部类,原理和第一种差不多
publicstaticvoidmain(String[] args){
List
//方法内-局部类
classHumanComparetorimplementsComparator{
@Override
publicintcompare(Human h1, Human h2){
returnh1.getAge() - h2.getAge();
}
}
Collections.sort(humans,newHumanComparetor());
System.out.println(humans);
}
第三种:基于第二种方法,局部类改为匿名类
publicstaticvoidmain(String[] args){
List
//匿名类
Collections.sort(humans,newComparator() {
@Override
publicintcompare(Human h1, Human h2){
returnh1.getAge() - h2.getAge();
}
});
System.out.println(humans);
}
第四种:使用lamdba表达式->这种形式
publicstaticvoidmain(String[] args){
List
//lamdba 表达式 ->
Collections.sort(humans, (Human h1, Human h2) -> h1.getAge() - h2.getAge());
System.out.println(humans);
}
第五种:借助Comparator和lamdba表达式多条件排序
publicstaticvoidmain(String[] args){
List
////lamdba 表达式 ::
Collections.sort(humans, Comparator.comparing(Human::getAge).thenComparing(Human::getName));
System.out.println(humans);
}
第六种:调用方式和第五种有区别,原理一样
publicstaticvoidmain(String[] args){
List
//直接用list.sort
humans.sort(Comparator.comparing(Human::getAge).thenComparing(Human::getName));
System.out.println(humans);
}