目录
Collections.sort对list进行排序
java
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(2);
Collections.sort(list);
for (Integer integer : list) {
System.out.println(integer);
}
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("d");
list.add("c");
list.add("b");
Collections.sort(list);
for (String integer : list) {
System.out.println(integer);
}
}
运行结果
对象中某个属性进行排序
java
//升序
list.sort(Comparator.comparing(User::getName));
//降序
list.sort(Comparator.comparing(User::getName).reversed());
运行结果
通过比较器进行比较
java
//升序降级通过改变其中的参数确定
Collections.sort(list, new Comparator<User>(){
@Override
public int compare(User stu1, User stu2) {
// TODO Auto-generated method stub
return stu2.getName().compareTo(stu1.getName());
}
});
运行结果
JAVA8特性Stream流进行排序
java
//升序
List<User> collect = list.stream().sorted(Comparator.comparing(User::getName))
.collect(Collectors.toList());
//降序
List<User> collect = list.stream().sorted(Comparator.comparing(User::getName).reversed())
.collect(Collectors.toList());
Stream升降序组合使用
java
//先按照年龄进行升序,然后按照姓名降序
list.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getName).reversed()).collect(Collectors.toList())
.forEach(s->{
System.out.println(s.getName()+s.getAge());
});
运行结果