使用Java 8按时间间隔对LocalDateTime对象进行分组 [英] Grouping LocalDateTime objects in intervals using Java 8
问题描述
我有以下格式的列表,并且希望将此列表按分钟间隔进行分组.
I have a List in the following format and I want to group this List into minute intervals.
List<Item> myObjList = Arrays.asList(
new Item(LocalDateTime.parse("2020-09-22T00:13:36")),
new Item(LocalDateTime.parse("2020-09-22T00:17:20")),
new Item(LocalDateTime.parse("2020-09-22T01:25:20")),
new Item(LocalDateTime.parse("2020-09-18T00:17:20")),
new Item(LocalDateTime.parse("2020-09-19T00:17:20")));
例如,给定间隔10分钟,列表的前2个对象应该在同一组中,第3个对象应该在不同的组中,依此类推.
For example, given an interval of 10 minutes the first 2 objects of the list should be in the same group, the 3rd should be in a different group, etc.
可以使用Java的8 groupingBy
函数将此列表分组为间隔吗?
Can this List be grouped into intervals using Java's 8 groupingBy
function?
我的解决方案是将列表中的每个日期与列表中的所有其他日期进行比较,并将相差X分钟的日期添加到新列表中.这似乎是非常缓慢且"hacky"的解决方法,我想知道是否有更稳定的解决方案.
My solution is to compare every date in the list with all the other dates in the list and add the dates that differ X minutes in a new List. This seems to be very slow and 'hacky' workaround and I wonder if there is a more stable solution.
推荐答案
可以使用 LocalDateTime
对象分成10分钟间隔的列表.您必须修改此代码段才能与您的Item
类一起使用,但是逻辑是相同的.
It is possible to use Collectors#groupingBy
to group LocalDateTime
objects into lists of 10-minute intervals. You'll have to adapt this snippet to work with your Item
class, but the logic is the same.
List<LocalDateTime> myObjList = Arrays.asList(
LocalDateTime.parse("2020-09-22T00:13:36"),
LocalDateTime.parse("2020-09-22T00:17:20"),
LocalDateTime.parse("2020-09-22T01:25:20"),
LocalDateTime.parse("2020-09-18T00:17:20"),
LocalDateTime.parse("2020-09-19T00:17:20")
);
System.out.println(myObjList.stream().collect(Collectors.groupingBy(time -> {
// Store the minute-of-hour field.
int minutes = time.getMinute();
// Determine how many minutes we are above the nearest 10-minute interval.
int minutesOver = minutes % 10;
// Truncate the time to the minute field (zeroing out seconds and nanoseconds),
// and force the number of minutes to be at a 10-minute interval.
return time.truncatedTo(ChronoUnit.MINUTES).withMinute(minutes - minutesOver);
})));
输出
{
2020-09-22T00:10=[2020-09-22T00:13:36, 2020-09-22T00:17:20],
2020-09-19T00:10=[2020-09-19T00:17:20],
2020-09-18T00:10=[2020-09-18T00:17:20],
2020-09-22T01:20=[2020-09-22T01:25:20]
}
这篇关于使用Java 8按时间间隔对LocalDateTime对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!