java List集合中元素排序
1、java8
Person person1 = new Person("tom", 15);
Person person2 = new Person("jack", 26);
Person person3 = new Person("lucy", 12);
List<Person> list = Arrays.asList(person1,person2,person3);
//正序
list.stream().sorted(Comparator.comparing(Person::getAge))
.collect(Collectors.toList()).forEach(person -> {
System.out.println(person.getAge());
});
//倒序
list.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.collect(Collectors.toList()).forEach(person -> {
System.out.println(person.getAge());
});
2、Collections.sort()方法进行简单排序
List<Integer> list = new ArrayList<Integer>();
list.add(new Integer(5));
list.add(new Integer(13));
list.add(new Integer(4));
list.add(new Integer(9));
Collections.sort(list);
System.out.println(list.toString());
输出结果:[4, 5, 9, 13]
3、list参数类型相对复杂的排序
List<User> list = new ArrayList<User>();
list.add(new User("张三", 5));
list.add(new User("李四", 30));
list.add(new User("王五", 19));
list.add(new User("赵六", 17));
Collections.sort(list); // 按年龄排序
System.out.println(list.toString());
//实体类实现Comparable 接口
class User implements Comparable<User> {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public int compareTo(User o) {
return this.age - o.age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
4、匿名内部类实现排序
List<User> list = new ArrayList<User>();
list.add(new User("张三", 5));
list.add(new User("李四", 30));
list.add(new User("王五", 19));
list.add(new User("赵六", 17));
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
int tmp = u1.getAge() - u2.getAge();
if (tmp > 0) {
return 1;
} else if (tmp < 0) {
return -1;
}
return 0; //相等为0
}
}); // 按年龄排序
System.out.println(list.toString());