Collections对List集合中的数据进行排序

有时候需要对集合中的元素按照一定的规则进行排序,这就需要用到

Java中提供的对集合进行操作的工具类Collections,其中的sort方法


No1.先看一个简单的例子:

     public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
nums.add(2);
nums.add(9);
nums.add(7);
nums.add(1);
nums.add(0);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
}

结果如下:

[2, 9, 7, 1, 0]
[0, 1, 2, 7, 9]


建立一个No2代码要用的entity,如下:

 import java.util.Date;

 public class Record implements Comparable<Record> {
private String name;
private int age;
private Date start; public Record(String name, int age, Date start) {
this.name = name;
this.age = age;
this.start = start;
} 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 Date getStart() {
return start;
} public void setStart(Date start) {
this.start = start;
} @Override
public int compareTo(Record o) {
int nameIndex = this.name.compareTo(o.name);
int ageIndex = 0;
int startIndex = 0;
// 姓名一样则比较年龄
if (nameIndex == 0) {
ageIndex = this.age - o.age;
}
// 年龄一样则比较开始时间
if (ageIndex == 0) {
boolean isAfter = this.start.after(o.start);
if (isAfter) {
startIndex = 1;
} else {
startIndex = -1;
}
}
return nameIndex+ageIndex+startIndex;
} }

No2.稍复杂一些的排序:

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; public class ListOrder {
public static void main(String[] args) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
List<Record> records = new ArrayList<Record>();
records.add(new Record("a", 2, df.parse("2015-12-16")));
records.add(new Record("d", 8, df.parse("2015-12-16")));
records.add(new Record("a", 1, df.parse("2019-12-16")));
records.add(new Record("x", 0, df.parse("2014-12-16")));
records.add(new Record("a", 1, df.parse("2018-12-16")));
for (Record record : records) {
System.out.println("name :" + record.getName() + " age :" + record.getAge() + " start :" + record.getStart());
}
Collections.sort(records);
System.out.println("--------------------------------------");
for (Record record : records) {
System.out.println("name :" + record.getName() + " age :" + record.getAge() + " start :" + record.getStart());
}
}
}

输出结果:

name :a age :2 start :Wed Dec 16 00:00:00 CST 2015
name :d age :8 start :Wed Dec 16 00:00:00 CST 2015
name :a age :1 start :Mon Dec 16 00:00:00 CST 2019
name :x age :0 start :Tue Dec 16 00:00:00 CST 2014
name :a age :1 start :Sun Dec 16 00:00:00 CST 2018
--------------------------------------
name :a age :1 start :Sun Dec 16 00:00:00 CST 2018
name :a age :1 start :Mon Dec 16 00:00:00 CST 2019
name :a age :2 start :Wed Dec 16 00:00:00 CST 2015
name :d age :8 start :Wed Dec 16 00:00:00 CST 2015
name :x age :0 start :Tue Dec 16 00:00:00 CST 2014


Collections提供的第二种排序方法sort(List<T> list, Comparator<? super T> c)

所使用的entity:

 import java.util.Date;

 public class Record {
private String name;
private int age;
private Date start; public Record(String name, int age, Date start) {
this.name = name;
this.age = age;
this.start = start;
} 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 Date getStart() {
return start;
} public void setStart(Date start) {
this.start = start;
}
}

No3:代码:

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class ListOrder { public static void main(String[] args) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
List<Record> records = new ArrayList<Record>();
records.add(new Record("a", 2, df.parse("2015-12-16")));
records.add(new Record("d", 8, df.parse("2015-12-16")));
records.add(new Record("a", 1, df.parse("2019-12-16")));
records.add(new Record("x", 0, df.parse("2014-12-16")));
records.add(new Record("a", 1, df.parse("2018-12-16")));
for (Record record : records) {
System.out
.println("name :" + record.getName() + " age :" + record.getAge() + " start :" + record.getStart());
}
Collections.sort(records, new Comparator<Record>() {
@Override
public int compare(Record r1, Record r2) {
int nameIndex = r1.getName().compareTo(r2.getName());
int ageIndex = 0;
int startIndex = 0;
// 姓名一样则比较年龄
if (nameIndex == 0) {
ageIndex = r1.getAge() - r2.getAge();
}
// 年龄一样则比较开始时间
if (ageIndex == 0) {
boolean isAfter = r1.getStart().after(r2.getStart());
if (isAfter) {
startIndex = 1;
} else {
startIndex = -1;
}
}
return nameIndex + ageIndex + startIndex;
}
});
System.out.println("--------------------------------------");
for (Record record : records) {
System.out
.println("name :" + record.getName() + " age :" + record.getAge() + " start :" + record.getStart());
}
}
}

結果:

name :a age :2 start :Wed Dec 16 00:00:00 CST 2015
name :d age :8 start :Wed Dec 16 00:00:00 CST 2015
name :a age :1 start :Mon Dec 16 00:00:00 CST 2019
name :x age :0 start :Tue Dec 16 00:00:00 CST 2014
name :a age :1 start :Sun Dec 16 00:00:00 CST 2018
--------------------------------------
name :a age :1 start :Sun Dec 16 00:00:00 CST 2018
name :a age :1 start :Mon Dec 16 00:00:00 CST 2019
name :a age :2 start :Wed Dec 16 00:00:00 CST 2015
name :d age :8 start :Wed Dec 16 00:00:00 CST 2015
name :x age :0 start :Tue Dec 16 00:00:00 CST 2014


reference:

https://blog.csdn.net/veryisjava/article/details/51675036

https://www.jb51.net/article/72284.htm

https://blog.csdn.net/u012901117/article/details/76853113

java中对List中的元素进行排序的更多相关文章

  1. java中TreeSet集合如何实现元素的判重

    /* 看一下部分的TreeSet源码.... public class TreeSet<E> extends AbstractSet<E> implements Navigab ...

  2. java集合 collection-list-ArrayList 将自定义对象作为元素存到ArrayList集合中,并去除重复元素。

    import java.util.*; /* 将自定义对象作为元素存到ArrayList集合中,并去除重复元素. 比如:存人对象.同姓名同年龄,视为同一个人.为重复元素. 思路: 1,对人描述,将数据 ...

  3. Java 去除 ArrayList 集合中的重复元素

    // One practice package Collection; import java.util.ArrayList; import java.util.Iterator; // 去除 Arr ...

  4. Java-Runoob-高级教程-实例-数组:14. Java 实例 – 在数组中查找指定元素

    ylbtech-Java-Runoob-高级教程-实例-数组:14. Java 实例 – 在数组中查找指定元素 1.返回顶部 1. Java 实例 - 在数组中查找指定元素  Java 实例 以下实例 ...

  5. Java-Runoob-高级教程-实例-数组:10. Java 实例 – 查找数组中的重复元素-un

    ylbtech-Java-Runoob-高级教程-实例-数组:10. Java 实例 – 查找数组中的重复元素 1.返回顶部 1. Java 实例 - 查找数组中的重复元素  Java 实例 以下实例 ...

  6. Java如何删除数组中的元素?

    Java中,如何删除数组元素? 示例 以下示例显示如何从数组中删除元素. package com.yiibai; import java.util.ArrayList; public class Re ...

  7. Leetcode 703题数据流中的第K大元素(Kth Largest Element in a Stream)Java语言求解

    题目链接 https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/ 题目内容 设计一个找到数据流中第K大元素的类(class) ...

  8. java android 将 List中元素互换位置

    很多时候我要对List中的元素调换位置,这时候可以用如下代码,意思是将data中的index1与index2元素互换位置 //data 为List Collections.swap(data,inde ...

  9. leetcode.矩阵.378有序矩阵中第K小的元素-Java

    1. 具体题目 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素.请注意,它是排序后的第k小元素,而不是第k个元素. 示例: matrix = [ [ 1,  5, ...

  10. Java实现 LeetCode 703 数据流中的第K大元素(先序队列)

    703. 数据流中的第K大元素 设计一个找到数据流中第K大元素的类(class).注意是排序后的第K大元素,不是第K个不同的元素. 你的 KthLargest 类需要一个同时接收整数 k 和整数数组n ...

随机推荐

  1. 001 安装mysql

    在安装docker之后,安装一个mysql的容器试试手.可以参考违章: URL: https://www.cnblogs.com/limingxie/p/8655457.html

  2. ffmpeg x264安装

    fmpeg安装第三方编码器(encoder)库,ffmpeg编码h264(完) ffmpeg安装第三方编码器(encoder)库 关键词:ffmpeg.编码h264.第三方encoder 安装好了ff ...

  3. [原][landcover]全球地表植被样例图片

    图由南水之源提供,感谢    流socket  制作总结 原截图如下:按字母顺序排序 asphalt asphalt_bright asphalt_white brightRockOnly broad ...

  4. k8s之磁盘挂载持久化

  5. git clone 使用用户名和密码

    git clone http://邮箱(或用户名):密码@仓库 示例: 邮箱 xw@qq.com 密码: xw 仓库: http://git.test.com/abc/demo 注意: 邮箱中的 @ ...

  6. 转 mysql mysql命令行中执行sql的几种方式总结

    https://www.jb51.net/article/96394.htm 1.直接输入sql执行 MySQL> select now(); +---------------------+ | ...

  7. Spring Cloud Hystrix 服务容错保护 5.1

    Spring Cloud Hystrix介绍 在微服务架构中,通常会存在多个服务层调用的情况,如果基础服务出现故障可能会发生级联传递,导致整个服务链上的服务不可用为了解决服务级联失败这种问题,在分布式 ...

  8. FreeMarker的应用场景

      FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户的,而是一个Java类库,是一 ...

  9. SqlServer里,一条sql进行递归删除

    Server 2005中提供了公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多. 存储过程方法: create proc up_delete_ncla ...

  10. 【WAP触屏】YouKu视频弹窗播放组件

    (function(window){ /* youku api : http://open.youku.com/tools 调用方法 : LM_youkuPop.open('XODI5Mzk3MDAw ...