import com.alibaba.fastjson.JSON; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * stream 流根据集合的某个字段属性进行排序 */ public class streamDemo01 { public static void main(String[] args) { List<User> users = Arrays.asList( new User(101, "Jack"), new User(102, "Kreas"), new User(103, "Marry"), new User(104, "Timi"), new User(105, "Alice")); //自然序 List<User> collect = users.stream().sorted(Comparator.comparing(User::getId)).collect(Collectors.toList()); //倒序 List<User> collect1 = users.stream().sorted(Comparator.comparing(User::getId).reversed()).collect(Collectors.toList()); System.out.println(JSON.toJSONString(collect)); System.out.println(JSON.toJSONString(collect1)); } } 输出结果:
[{"id":101,"name":"Jack"},{"id":102,"name":"Kreas"},{"id":103,"name":"Marry"},{"id":104,"name":"Timi"},{"id":105,"name":"Alice"}]
[{"id":105,"name":"Alice"},{"id":104,"name":"Timi"},{"id":103,"name":"Marry"},{"id":102,"name":"Kreas"},{"id":101,"name":"Jack"}]
@Data public class User { // 用户ID private long id; // 用户名称 private String name; public User(long id, String name) { this.id = id; this.name = name; } }