Java8 Comparator排序方法实例详解
这篇文章主要介绍了Java8Comparator排序方法实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Java8中Comparator接口提供了一些静态方法,可以方便于我们进行排序操作,下面通过例子讲解下如何使用
对整数列表排序(升序)
Listlist=Arrays.asList(1,4,2,6,2,8); list.sort(Comparator.naturalOrder()); System.out.println(list);
对整数列表排序(降序)
Listlist=Arrays.asList(1,4,2,6,2,8); list.sort(Comparator.reverseOrder()); System.out.println(list);
根据对象属性(年龄)进行排序
publicclassTest{
publicstaticvoidmain(String[]args){
ListpersonList=newArrayList<>();
personList.add(newPerson("a",2));
personList.add(newPerson("b",4));
personList.add(newPerson("c",7));
//升序
personList.sort(Comparator.comparingInt(Person::getAge));
//降序
personList.sort(Comparator.comparingInt(Person::getAge).reversed());
System.out.println(personList);
}
publicstaticclassPerson{
privateStringname;
privateIntegerage;
publicPerson(Stringname,Integerage){
this.name=name;
this.age=age;
}
publicIntegergetAge(){
returnage;
}
//...toString方法
}
}
根据对象属性(价格、速度)进行排序,需要注意的是,排序有先后之分,不同的顺序会导致不同的结果
publicclassTest{
publicstaticvoidmain(String[]args){
Listlist=newArrayList<>();
list.add(newComputer("xiaomi",4000,6));
list.add(newComputer("sony",5000,4));
list.add(newComputer("dell",4000,5));
list.add(newComputer("mac",6000,8));
list.add(newComputer("micro",5000,6));
//先以价格(升序)、后再速度(升序)
list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed));
//先以速度(降序)、后再价格(升序)
list.sort(Comparator.comparingInt(Computer::getSpeed).reversed().thenComparingInt(Computer::getPrice));
//先以价格(降序)、后再速度(降序)
list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed).reversed());
System.out.println(list);
}
publicstaticclassComputer{
privateStringname;
privateIntegerprice;
privateIntegerspeed;
publicComputer(Stringname,Integerprice,Integerspeed){
this.name=name;
this.price=price;
this.speed=speed;
}
publicIntegergetPrice(){
returnprice;
}
publicvoidsetPrice(Integerprice){
this.price=price;
}
publicIntegergetSpeed(){
returnspeed;
}
publicvoidsetSpeed(Integerspeed){
this.speed=speed;
}
//...toString方法
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。