681人阅读 评论(0)

# Java 中 List 元素排序

## 方式一： List 中对象实现 Comparable 接口

1、 创建对象并实现 Comparable 接口

public class Cat implements Comparable<Cat> {
private String name;
private Integer order;

public Cat(String name, Integer order) {
super();
this.name = name;
this.order = order;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getOrder() {
return order;
}

public void setOrder(Integer order) {
this.order = order;
}

@Override
public int compareTo(Cat o) {
return this.getOrder().compareTo(o.getOrder());
}

@Override
public String toString() {
return "Cat [name=" + name + ", order=" + order + "]";
}
}

2、 调用 Collections.sort(List) 方法进行排序

public static void main(String[] args) {
List<Cat> catList = new ArrayList<>();
Cat cat1 = new Cat("name1", 1);
Cat cat2 = new Cat("name2", 2);
Cat cat3 = new Cat("name3", 3);
System.out.println("未排序： " + catList.toString());
//调用 Collections.sort() 方法进行排序
Collections.sort(catList);
System.out.println("排序后： " + catList.toString());
}

未排序： [Cat [name=name3, order=3], Cat [name=name1, order=1], Cat [name=name2, order=2]]

## 方式二： 重载 Collections.sort() 方法

1、 创建对象

public class Dog {
private String name;
private Integer order;

public Dog(String name, Integer order) {
super();
this.name = name;
this.order = order;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getOrder() {
return order;
}

public void setOrder(Integer order) {
this.order = order;
}

@Override
public String toString() {
return "Dog [name=" + name + ", order=" + order + "]";
}

}

2、 调用 Collections.sort(List, Comparator) 方法进行排序

public static void main(String[] args) {
List<Dog> dogList = new ArrayList<>();
Dog dog1 = new Dog("name1", 1);
Dog dog2 = new Dog("name2", 2);
Dog dog3 = new Dog("name3", 3);
System.out.println("未排序： " + dogList.toString());
//调用 Collections.sort() 方法进行排序，传入List 和 Comparator
Collections.sort(dogList, new Comparator<Dog>() {
@Override
public int compare(Dog o1, Dog o2) {
return o1.getOrder().compareTo(o2.getOrder());
}
});
System.out.println("排序后： " + dogList.toString());
}

未排序： [Dog [name=name3, order=3], Dog [name=name1, order=1], Dog [name=name2, order=2]]

Homepage: http://junkchen.com

个人资料
等级：
访问量： 17万+
积分： 2109
排名： 2万+
博客专栏
 Android开发 文章：8篇 阅读：65341