小例子
public static void main(String[] args) { List<User> list = new ArrayList<>(); list.add(new User(1, "猪头", 23)); list.add(new User(1, "猪头", 132)); list.add(new User(1, "猪头", 243)); list.add(new User(1, "猪头", 13)); list.add(new User(1, "猪头", 223)); list.add(new User(1, "猪头", 73)); list.add(new User(1, "猪头", 63)); //升序 List<User> resultList1 = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList()); //降序 List<User> resultList2 = list.stream().sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())).collect(Collectors.toList()); //limit截取 List<User> resultList3 = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).limit(3).collect(Collectors.toList()); System.out.println("升序"); for (User user:resultList1){ System.out.println(user.toString()); } System.out.println("降序"); for (User user:resultList2){ System.out.println(user.toString()); } System.out.println("截断流"); for (User user:resultList3){ System.out.println(user.toString()); } }
小例子
//limit截取 List<User> resultList3 = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).limit(3).collect(Collectors.toList());
完整输出
本文作者为DBC,转载请注明。