前言
记一下Java中List对象的三种排序方式,万一用得着呢(已经用着了)。
方案一
简单对象排序,如Integer对象,String对象等,代码如下:
public class SortTest {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>(); integerList.add(9); integerList.add(4); integerList.add(6); integerList.add(1); integerList.add(8); integerList.add(7); integerList.add(5); Collections.sort(integerList); for (Integer i : integerList){ System.out.println(i); } Collections.sort(integerList,Collections.reverseOrder()); for (Integer i : integerList){ System.out.println(i); } } }
|
public class SortTest { public static void main(String[] args) { List<Integer> integerList = new ArrayList<>(); integerList.add(9); integerList.add(4); integerList.add(6); integerList.add(1); integerList.add(8); integerList.add(7); integerList.add(5); integerList.sort(Integer::compareTo); for (Integer i : integerList){ System.out.println(i); } } }
|
方案二
自定义对象排序,可重写compareTo方法排序
public class SortTest {
public static void main(String[] args) {
List<User> integerList = new ArrayList<>(); integerList.add(new User("m",9)); integerList.add(new User("j",4)); integerList.add(new User("y",6)); integerList.add(new User("q",1)); integerList.add(new User("i",8)); integerList.add(new User("b",7)); integerList.add(new User("d",5)); integerList.sort(User::compareTo); for (User i : integerList){ System.out.println("name:" + i.getName() + ",sex:" + i.getSex()); } } }
class User{ private String name;
private Integer sex;
public User(String name, Integer sex){ this.name = name; this.sex = sex; }
public User(){}
public int compareTo(User user){ return this.getSex().compareTo(user.getSex()); }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getSex() { return sex; }
public void setSex(Integer sex) { this.sex = sex; } }
|
方案三
用匿名函数重写排序方法
public class SortTest {
public static void main(String[] args) {
List<User> integerList = new ArrayList<>(); integerList.add(new User("m",9)); integerList.add(new User("j",4)); integerList.add(new User("y",6)); integerList.add(new User("q",1)); integerList.add(new User("i",8)); integerList.add(new User("b",7)); integerList.add(new User("d",5)); integerList.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getSex() >= o2.getSex() ? 1 : -1; } }); for (User i : integerList){ System.out.println("name:" + i.getName() + ",sex:" + i.getSex()); } } }
class User{ private String name;
private Integer sex;
public User(String name, Integer sex){ this.name = name; this.sex = sex; }
public User(){}
public int compareTo(User user){ return user.getSex().compareTo(this.getSex()); }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getSex() { return sex; }
public void setSex(Integer sex) { this.sex = sex; } }
|