Java使用Collections工具类对List集合进行排序
时间:2021-05-24 08:50:10|栏目:JAVA代码|点击: 次
这篇文章主要介绍了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()+"";
}
}
栏 目:JAVA代码
下一篇:基于Java注解(Annotation)的自定义注解入门介绍
本文标题:Java使用Collections工具类对List集合进行排序
本文地址:http://www.codeinn.net/misctech/127852.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




