使用流进行排序
/**
* @description: 排序对象
* @datetime 2023年 05月 08日 16:51
* @version: 1.0
*/
public class Human {
private String name;
private int age;
public Human() {
}
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class PaiXu {
public static void main(String[] args) {
ArrayList<Human> humans = new ArrayList<Human>() {
{
add(new Human("guorao", 10));
add(new Human("mako", 12));
add(new Human("hel", 30));
add(new Human("lin", 28));
}
};
// 倒叙
//List<Human> collect = humans.stream().sorted(Comparator.comparingInt(Human::getAge).reversed()).collect(Collectors.toList());
// 升序
List<Human> collect = humans.stream().sorted(Comparator.comparingInt(Human::getAge)).collect(Collectors.toList());
System.out.println("collect = " + JSON.toJSONString(collect));
}
}
使用Collections 工具类排序
public class PaiXu {
public static void main(String[] args) {
//Collections 排序
collectionsSort();
}
private static void collectionsSort() {
ArrayList<Human> humans = new ArrayList<Human>() {
{
add(new Human("guorao", 10));
add(new Human("mako", 12));
add(new Human("hel", 30));
add(new Human("lin", 28));
}
};
// 自定义比较器
//Collections.sort(humans, new Comparator<Human>(){
// //这样实现接口不用再专门写一格实现类了。
// public int compare(Human s1, Human s2) {
// // TODO 自动生成的方法存根
// return s1.getAge() - s2.getAge();//升序
// //return s2.getAge() - s1.getAge();//降序
// }
//});
Collections.sort(humans, Comparator.comparingInt(s -> s.getAge()));
System.out.println("humans = " + JSON.toJSONString(humans));
}
}
版权声明:本文为lingFei_y原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。