Stream通道流支持两种排序方式:sorted()自然排序;sorted(Comparator comp)。

sorted()自然排序:产生一个新流,流中每个序列按自然排序的方式进行排序。 sorted(Comparator comp):产生一个新流,流中的每个序列按自定义的比较器排序进行排序

一、sorted()

  1. public static void main(String[] args) throws InterruptedException {
  2. List<String> list1 = new ArrayList<>();
  3. list1.add("2");
  4. list1.add("1");
  5. list1.add("3");
  6. Stream<String> stream1 = list1.stream().sorted();
  7. stream1.forEach(p -> System.out.println(p));
  8. }

输出结果

  1. 1
  2. 2
  3. 3

二、sorted(Comparator comp)

  1. public static void main(String[] args) throws InterruptedException {
  2. List<Order> list = new ArrayList<>();
  3. Order order1 = new Order(LocalDateTime.now(), 1);
  4. Thread.sleep(2000);
  5. Order order2 = new Order(LocalDateTime.now(), 2);
  6. Thread.sleep(2000);
  7. Order order3 = new Order(LocalDateTime.now(), 3);
  8. Thread.sleep(2000);
  9. Order order4 = new Order(LocalDateTime.now(), 4);
  10. list.add(order2);
  11. list.add(order1);
  12. list.add(order3);
  13. list.add(order4);
  14. Stream<Order> stream = list.stream().sorted((o1, o2) -> {
  15. if (o1.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() - o2.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() >= 0) {
  16. return o1.getOrderTime().compareTo(o2.getOrderTime());
  17. } else {
  18. return o1.getOrderTime().compareTo(o2.getOrderTime());
  19. }
  20. });
  21. stream.forEach(p -> System.out.println(p));
  22. }

输出结果

  1. Order{orderTime=2018-08-09T15:59:28.458, orderId=1}
  2. Order{orderTime=2018-08-09T15:59:30.460, orderId=2}
  3. Order{orderTime=2018-08-09T15:59:32.461, orderId=3}
  4. Order{orderTime=2018-08-09T15:59:34.461, orderId=4}

三、获取排序的第一个元素

  1. public static void main(String[] args) throws InterruptedException {
  2. List<Order> list = new ArrayList<>();
  3. Order order1 = new Order(LocalDateTime.now(), 1);
  4. Thread.sleep(2000);
  5. Order order2 = new Order(LocalDateTime.now(), 2);
  6. Thread.sleep(2000);
  7. Order order3 = new Order(LocalDateTime.now(), 3);
  8. Thread.sleep(2000);
  9. Order order4 = new Order(LocalDateTime.now(), 4);
  10. list.add(order2);
  11. list.add(order1);
  12. list.add(order3);
  13. list.add(order4);
  14. Stream<Order> stream = list.stream().sorted((o1, o2) -> {
  15. if (o1.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() - o2.getOrderTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() >= 0) {
  16. return o1.getOrderTime().compareTo(o2.getOrderTime());
  17. } else {
  18. return o1.getOrderTime().compareTo(o2.getOrderTime());
  19. }
  20. });
  21. Optional<Order> first = stream.findFirst();
  22. System.out.println(first);
  23. Order order = first.get();
  24. System.out.println(order);
  25. }

输出结果

  1. Optional[Order{orderTime=2018-08-09T16:47:26.415, orderId=1}]
  2. Order{orderTime=2018-08-09T16:47:26.415, orderId=1}

转载 https://blog.csdn.net/qinaye/article/details/81539899