Java按照List内存储的对象的某个字段进行排序的实例
作者:jingxian 时间:2023-12-11 11:58:35
关键点:将List内存储的对象实现Comparable类,重写它的compareTo()方法即可
Bean:
package chc;
public class StuVo implements Comparable<StuVo>{
private String id;
private String name;
private Integer age;
public StuVo(String id, String name, Integer age) {
this.id=id;
this.name=name;
this.age=age;
}
public int compareTo(StuVo stu) {
return this.name.compareTo(stu.getName());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Demo:
package chc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ArrayListSortDemo {
public static void main(String[] args) {
List<StuVo> stuList=new ArrayList<StuVo>();
StuVo stu=new StuVo("1","h小明",11);
stuList.add(stu);
stu=new StuVo("2","d阿熊",15);
stuList.add(stu);
stu=new StuVo("3","a张三",10);
stuList.add(stu);
stu=new StuVo("4","b李四",15);
stuList.add(stu);
Collections.sort(stuList);
Iterator<StuVo> it =stuList.iterator();
while(it.hasNext()){
System.out.println(it.next().getName());
}
}
}
标签:list,某个,字段,排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#导出pdf的实现方法(浏览器不预览直接下载)
2023-11-04 05:48:10
Java8 CompletableFuture 异步多线程的实现
2023-07-21 08:07:15
![](https://img.aspxhome.com/file/2023/8/57708_0s.jpg)
mybatis-plus 查询传入参数Map,返回List<Map>方式
2022-01-05 13:39:24
![](https://img.aspxhome.com/file/2023/2/72592_0s.png)
Java等待唤醒机制线程通信原理解析
2022-03-31 00:37:21
![](https://img.aspxhome.com/file/2023/7/79867_0s.png)
springboot大文件上传、分片上传、断点续传、秒传的实现
2023-06-16 02:18:30
Android抛物线下载动画制作过程
2022-05-15 21:39:57
![](https://img.aspxhome.com/file/2023/0/114320_0s.gif)
C#实现单例模式的几种方法总结
2023-10-13 16:33:55
基于c# Task自己动手写个异步IO函数
2021-08-06 12:07:56
![](https://img.aspxhome.com/file/2023/4/108664_0s.png)
Java如何实现自定义异常类
2023-06-21 23:44:01
Android中通过RxJava进行响应式程序设计的入门指南
2023-06-27 08:17:46
JAVA的Random类的用法详解
2022-07-22 00:05:58
java中单例模式讲解
2022-05-22 14:24:07
![](https://img.aspxhome.com/file/2023/5/60335_0s.png)
Android编程实现图片背景渐变切换与图层叠加效果
2021-10-10 06:04:03
![](https://img.aspxhome.com/file/2023/5/138515_0s.jpg)
Java使用BigDecimal精确运算浮点数
2023-08-11 09:47:11
java.lang.OutOfMemoryError 错误整理及解决办法
2021-09-23 04:09:51
Struts2下拉框实例解析
2021-09-16 16:29:59
![](https://img.aspxhome.com/file/2023/9/61399_0s.jpg)
Android SurfaceView拍照录像实现方法
2022-06-18 17:07:20
简单讲解Android开发中触摸和点击事件的相关编程方法
2023-03-30 12:29:10
解析C#设计模式编程中备忘录模式的运用
2023-06-10 11:40:00
![](https://img.aspxhome.com/file/2023/8/71768_0s.jpg)
Android中的windowSoftInputMode属性详解
2022-11-14 06:17:40
![](https://img.aspxhome.com/file/2023/4/138184_0s.png)