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);
- }
- }
- Collections.sort(list);
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);
- }
- }
- }
//自己测试的 好用 List<A> list1 = new ArrayList<A>(); A a = new A(); a.setName("滴滴"); A b = new A(); b.setName("大哥哥"); A c = new A(); c.setName("李莲英"); A d = new A(); d.setName("杨坤"); A e = new A(); e.setName("李连杰"); A f = new A(); f.setName("成员"); A g = new A(); g.setName("赵润发"); A h = new A(); h.setName("欧阳娜娜"); list1.add(a); list1.add(b); list1.add(c); list1.add(d); list1.add(e); list1.add(f); list1.add(g); list1.add(h); Collections.sort(list1, new Comparator<A>() { @Override public int compare(A o1, A o2) { Comparator<Object> com = Collator.getInstance(java.util.Locale.CHINA); return com.compare(o1.getName(), o2.getName()); } }); for (int i = 0; i < list1.size(); i++) { System.out.println(list1.get(i).getName()); }
jdk自带的Collator包涵的汉字太少了,对一些生僻的姓氏不能进行排序。推荐使用:
- import com.ibm.icu.text.Collator;
是ibm开发的针对编码的工具包,非常好用。附pom文件:
- <dependency>
- <groupId>com.ibm.icu</groupId>
- <artifactId>icu4j</artifactId>
- <version>57.1</version>
- </dependency>