按小时分组时间戳

Chr*_*ian 2 java

我有一个时间戳列表,想将它们分组到小时(基于 24 小时)

例子:

List<Long> timestamps = new ArrayList<>();
//timestamps would contains 100 timestamps from over the last few days.

Now I want a map:
Map<String, List<Long>> groupedMap = new HashMap<>();

groupedMap would contain something like

{
   03.02.2015 - 12:00: [1234564321,1234564322,1234564323],
   03.02.2015 - 13:00: [12346664321,12346664323,12346664323]
}
Run Code Online (Sandbox Code Playgroud)

我使用的是 Java 8。执行此操作的最有效方法是什么?

Car*_*los 5

假设时间戳是从 1/1/1970 开始的 unix 秒偏移量,您可以使用 mod 函数来存储时间戳:

long bucket = timestamp - (timestamp % 3600);
Run Code Online (Sandbox Code Playgroud)

这将删除任何时间戳中超过一小时的任何秒数。