有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java按LocalDate排序映射流

我有一个类客户机,它包含一个订单列表,还包含一个LocalDate order_date

使用Java8流,我想按日期对订单列表进行排序

我有以下代码:

clients.getOrders().stream().map(Order::getDate).sorted(LocalDate::compareTo)).forEach(System.out::println)

但这绝对不行。我也试过使用sorted(Comparator.comparing(Order::getDate)),但它打印的是相同的

编辑

日期是不同的,我的全部代码是这样的

clients.stream().filter(client -> client.getOrders() != null).flatMap(c -> c.getOrders().stream().map(Order::getDate).sorted(LocalDate::compareTo)).forEach(System.out::println)

我得到的结果是

2019-02-17
2019-12-05
2020-03-15
2018-10-05
2020-07-15
2021-01-01

Process finished with exit code 0

我想要这个

2018-10-05
2019-02-17
2019-12-05
2020-03-15
2020-07-15
2021-01-01

共 (2) 个答案

  1. # 1 楼答案

    我想你选错了。如果先使用flatMap,然后再使用sorted,它应该可以工作

    clients.stream().filter(client -> client.getOrders() != null).flatMap(c -> c.getOrders().stream()).sorted(Comparator.comparing(Order::getDate)).forEach(System.out::println)
    
  2. # 2 楼答案

    更新 问题中的实现似乎调用了客户机。getOrders()多次。 不确定client.getOrders()每次调用时是否返回相同的结果。此外,它只是对日期进行排序,而不是对订单进行排序

    下面的代码只进行一次client.getOrders()调用并对顺序进行排序

    final List<Order> orders = clients.stream().map(clients -> client.getOrders())
    .filter(Objects::nonNull)
    .flatMap(orders -> orders.stream()) 
    .sorted(Comparator.comparing(Order::getDate))
    .collect(Collectors.toList());
    //Printing orders' dates
    orders.stream().map(Order::getDate).forEach(System.out::println);
    

    基于第一个问题版本的信息

    根据可用的原始信息,这应该正常工作:

    clients.getOrders().stream()
    .sorted(Comparator.comparing(Order::getDate)) 
    .forEach(System.out::println)
    

    但你已经说过你试过了

    另一种方法是使用集合

    final List<Order> orders=clients.getOrders();
    Collections.sort(orders,Comparator.comparing(Order::getDate));
    orders.stream().forEach(System.out::println);