Mehdi :
I have an Order object
public class Order{
private Date orderDate;
//other fields + getters & setters
}
And a List of Orders (List< Orders>). Now I want to group this list of orders based on similar orderDate (similar in here means, same year, month and day) and produce a map like this:
Map<Date, List<Order>> orderMap = new HashMap<>();
How to do this in Java 8+ ?
Take note we might have similar date but different timestamp which means we want to based it on "year, month, day"
Scorix :
I don't really support the point of doing everything with streams, but you can do it with a hard convertion way.
List<Order> orders = ... your list ...
Map<Date, List<Order>> orderMap = orders.stream().collect(Collectors.groupingBy(order->{
//Converting from Date to Instant
Instant dateInstant = order.getOrderDate().toInstant();
//Converting Instant to LocalDateTime and setting it to the start of the day
LocalDateTime dateTime = dateInstant.atZone(ZoneId.systemDefault()).toLocalDate().atStartOfDay();
//Converting it back to an instant
Instant startOfDayInstant = dateTime.atZone(ZoneId.systemDefault()).toInstant();
//Returning the util date
return Date.from(startOfDayInstant);
}));
This is under the circumstance that you need util date. Otherwise I support the answer from michalk
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=310274&siteId=1