List 中的ArrayList本身是按照添加顺序排列的,但是有时候想自定义排序方式怎么办呢?
1、List<Record>中的Record 实现 Comparable<Record>接口并复写compareto方法
- public class Record implements Comparable<Record> {
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public int compareTo(Record o) {
- return name.compareTo(o.name);
- }
- }
然后再比较的时候调用实现排序
2、第二种方式,通过内部类实现排序
- public static void main(String[] args) {
- List<Record> list = new ArrayList<Record>();
- Collections.sort(list, new Comparator<Record>() {
- public int compare(Record o1, Record o2) {
- return o1.getName().compareTo(o2.getName())
- };
- });
- }
附:按照汉字的字典序列进行排序
- package com.datayes.ecoinfo;
-
- import java.text.Collator;
- 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<String> list = new ArrayList<String>();
- list.add("你");
- list.add("好");
- list.add("啊");
- Collections.sort(list, new Comparator<String>() {
- @Override
- public int compare(String o1, String o2) {
- Comparator<Object> com = Collator.getInstance(java.util.Locale.CHINA);
- return com.compare(o1, o2);
-
- }
- });
-
- for (String temp : list) {
- System.out.println(temp);
- }
- }
- }
jdk自带的Collator包涵的汉字太少了,对一些生僻的姓氏不能进行排序。推荐使用:
- import com.ibm.icu.text.Collator;
是ibm开发的针对编码的工具包,非常好用。附pom文件:
- <dependency>
- <groupId>com.ibm.icu</groupId>
- <artifactId>icu4j</artifactId>
- <version>57.1</version>
- </dependency>