Home > database >  Sort by LocalDate a mapped stream
Sort by LocalDate a mapped stream

Time:10-20

I have a class client that contains a list of Orders, that also contains a LocalDate order_date.

And using Java 8 streams, I want to sort my list of Orders by Date.

I have the following code :

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

But that does absolutely not sort. I also tried with sorted(Comparator.comparing(Order::getDate)) but it prints the same.

EDIT :

Dates are differents and my whole code line is this

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

And the output I have is

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

Process finished with exit code 0

and I want this

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

CodePudding user response:

I think you are sorting the wrong stream. If you use flatMap first and then sorted it should work.

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

CodePudding user response:

Update It seems that the implementation in the question calls client.getOrders() many times. Not sure if client.getOrders() returns the same result every time it is called. Also it is sorting only the dates, not the orders.

The following code only makes a single client.getOrders() invocation and sorts the orders.

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);

Information based on first question version

Based on the original information available, this should normally work:

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

But you already mention you tried it.

Another way could be using collections.

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