我有一個包含Orders串列的類客戶端,其中還包含一個.LocalDate order_date
并且使用 Java 8 流,我想按日期對我的訂單串列進行排序。
我有以下代碼:
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
uj5u.com熱心網友回復:
我認為您正在對錯誤的流進行排序。如果您flatMap先使用然后sorted它應該可以作業。
clients.stream().filter(client -> client.getOrders() != null).flatMap(c -> c.getOrders().stream()).sorted(Comparator.comparing(Order::getDate)).forEach(System.out::println)
uj5u.com熱心網友回復:
更新
似乎問題中的實作多次呼叫 client.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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333898.html
上一篇:如何通過物件的屬性值對物件陣列進行排序,該屬性值本身不是自然可比的,但具有基于規則的優先級?
下一篇:按降序對二維陣列元素進行排序
