Java使用Collections工具类对List集合进行排序
作者:时间-海 时间:2022-10-12 23:59:12
这篇文章主要介绍了Java使用Collections工具类对List集合进行排序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一、说明
使用Collections工具类的sort方法对list进行排序
新建比较器Comparator
二、代码
排序:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
//创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中
Student s1 = new Student();
s1.setAge(20);
Student s2 = new Student();
s2.setAge(19);
Student s3 = new Student();
s3.setAge(21);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("排序前:"+list);
Collections.sort(list, new Comparator<Student>(){
/*
* int compare(Student o1, Student o2) 返回一个基本类型的整型,
* 返回负数表示:o1 小于o2,
* 返回0 表示:o1和o2相等,
* 返回正数表示:o1大于o2。
*/
public int compare(Student o1, Student o2) {
//按照学生的年龄进行升序排列
if(o1.getAge() > o2.getAge()){
return 1;
}
if(o1.getAge() == o2.getAge()){
return 0;
}
return -1;
}
});
System.out.println("排序后:"+list);
}
}
Student类:
class Student{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return getAge()+"";
}
}
来源:https://www.cnblogs.com/wslook/p/9385871.html
标签:java,collections,工具类,list,集合,排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java中避免过多if-else的几种方法
2023-11-28 13:07:09
Java java.sql.Timestamp时间戳案例详解
2023-11-10 13:50:47
spring boot集成smart-doc自动生成接口文档详解
2023-11-28 23:08:02
![](https://img.aspxhome.com/file/2023/3/60773_0s.png)
Flutter图片缓存管理ImageCache原理分析
2023-08-20 23:26:19
学习Java HashMap,看这篇就够了
2023-11-11 11:18:56
![](https://img.aspxhome.com/file/2023/2/59422_0s.png)
Mybatis初始化知识小结
2023-11-01 13:59:27
![](https://img.aspxhome.com/file/2023/8/58708_0s.png)
Java面试synchronized偏向锁后hashcode存址
2023-08-09 09:15:06
![](https://img.aspxhome.com/file/2023/0/57920_0s.png)
ElasticSearch学习之ES Mapping实战示例
2023-11-25 06:12:25
详解Android Flutter中SliverAppBar的使用教程
2023-06-23 12:11:27
![](https://img.aspxhome.com/file/2023/7/97867_0s.jpg)
java实现163邮箱发送邮件到qq邮箱成功案例
2023-09-18 02:38:09
SpringMVC解析JSON请求数据问题解析
2023-06-02 21:41:32
![](https://img.aspxhome.com/file/2023/8/60578_0s.png)
简单实现安卓里百度地图持续定位
2023-07-29 07:59:22
Flutter倒计时/计时器的实现代码
2023-07-01 03:50:50
![](https://img.aspxhome.com/file/2023/5/103895_0s.jpg)
Java实现考试系统
2023-11-18 04:15:03
![](https://img.aspxhome.com/file/2023/2/59602_0s.jpg)
Spring Boot缓存实战之Redis 设置有效时间和自动刷新缓存功能(时间支持在配置文件中配置)
2023-11-11 01:57:18
![](https://img.aspxhome.com/file/2023/3/59053_0s.png)
Java基础之面向对象机制(多态、继承)底层实现
2023-11-12 02:59:59
入门JDK集合之HashMap解析
2023-11-24 02:45:03
![](https://img.aspxhome.com/file/2023/1/59901_0s.png)
java调用外部程序的方法及代码演示
2023-11-13 22:42:55
synchronized及JUC显式locks 使用原理解析
2023-08-05 03:28:41
SpringBoot 如何从配置文件读取值到对象中
2023-10-13 15:43:15
![](https://img.aspxhome.com/file/2023/3/58533_0s.png)