Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Java 8 Dates in intervals

Using Java 8 java.time framework, how can Dates be grouped into intervals? For example, every 10 minutes as an interval, and a list of given LocalTime

List<LocalTime> list = Arrays.asList(LocalTime.of(0,9),LocalTime.of(0,11),LocalTime.of(0,19));

If grouping with an interval of 10 minutes, LocalTime.of(0,9) should be in the first group, but LocalTime.of(0,11),LocalTime.of(0,19) in the second interval.

like image 973
user140547 Avatar asked Dec 23 '15 15:12

user140547


1 Answers

Using the Java 8 time API, this can be done quite convienently:

Map<Integer, List<LocalTime>> map = 
     list.stream()
          .collect(Collectors.
                 groupingBy(x -> x.get(ChronoField.MINUTE_OF_DAY) / 10)
                  );

This example would use a LocalTime and group your posts in groups of 10 minutes.

Note: This was originally an answer to Java 8 complex custom collector , but since it did not address OPs question, and got some upvotes, I deleted it and wrote a question for it. Changed order of calls according to JodaStephen's comment

like image 98
user140547 Avatar answered Oct 15 '22 09:10

user140547