How to group values from a list with Java Stream API (groupingBy collector)?

Valeriy :

I have list of Entry objects. Entry is a:

class Entry {
   private final Date date;
   private final String value;

   // constructor
   // getters
}

I need to group these entries by day. For example,

2011-03-21 09:00 VALUE1
2011-03-21 09:00 VALUE2
2011-03-22 14:00 VALUE3
2011-03-22 16:00 VALUE4
2011-03-21 16:00 VALUE5

Should be grouped:

2011-03-21
    VALUE1
    VALUE2
    VALUE5

2011-03-22
    VALUE3
    VALUE4

I want to get a Map<Date, List<Entry>>. How can I get this using the Stream API (groupingBy collector)?

My attempt below:

final Map<Date, List<Entry>> entries =
        list.stream().collect(Collectors.groupingBy(request -> {
        final Calendar ogirinal = Calendar.getInstance();
        ogirinal.setTime(request.getDate());

        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, ogirinal.get(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.MONTH, ogirinal.get(Calendar.MONTH));
        cal.set(Calendar.YEAR, ogirinal.get(Calendar.YEAR));

        return cal.getTime();
    }));

Output:

2011-03-21
    VALUE1
2011-03-21
    VALUE2
2011-03-22
    VALUE3
    VALUE4
2011-03-21
    VALUE5
Juan Carlos Mendoza :

Again don't understand why you are using java.util.Date when you can use LocalDateTime for example. But here goes my attempt:

Map<Date, List<Entry>> entries = list.stream().collect(Collectors.groupingBy(e ->
    // easier way to truncate the date
    Date.from(e.getDate().toInstant().truncatedTo(ChronoUnit.DAYS)))
);

DEMO

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458165&siteId=1