list集合的排序
使用常用的sort方法排序和stream流的方式排序
package com.liucy.meiriyilian.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author liucy
* @Date 2024/4/16 13:48
* @Desc list集合排序的方式
*/
public class ListSortDemo {
public static void main(String[] args) {
// List<User> userList = List.of(
// new User("111", "徐汇区", 20, 13564181485L),
// new User("222", "浦东新区", 25, 13654782145L),
// new User("333", "黄浦区", 30, 13765478921L)
// );
List<User> userList = new ArrayList<User>();
userList.add(new User("111", "徐汇区", 40, 13564181485L));
userList.add(new User("222", "浦东新区", 20, 13654782145L));
userList.add(new User("333", "黄浦区", 25, 13765478921L));
System.out.println("排序前");
userList.forEach(System.out::println);
// sortByCompare(userList);
sortByStream(userList);
}
/**
* 按照compare排序
* @param userList
*/
private static void sortByCompare(List<User> userList) {
Collections.sort(userList, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
}
});
System.out.println("排序后");
userList.forEach( user -> System.out.println(user.toString()));
}
private static void sortByStream(List<User> userList) {
userList = userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
System.out.println("排序后");
userList.forEach(System.out::println);
}
}
标签:list,System,userList,User,集合,new,排序,out
From: https://www.cnblogs.com/gushilcy/p/18138035