我有一个包含字段生成时间的对象列表,其中我通过 System.currentTimeInMills() 函数以长格式存储时间。数据如下:
List<MyObject> myObj = Arrays.asList(
new MyObject(time="1561473186140", name="123", status=200)
new MyObject(time="1561473186123", name="ABC", status=200)
new MyObject(time="1561473183435", name="ABC", status=200)
new MyObject(time="1561473185666", name="123", status=200)
new MyObject(time="1561473186132", name="ABC", status=200)
new MyObject(time="1561473183423", name="ABC", status=200)
new MyObject(time="1561473184242", name="123", status=200)
new MyObject(time="1561473186190", name="ABC", status=200)
new MyObject(time="1561473186098", name="ABC", status=200)
);
现在我必须根据小时对数据进行分组。比如从上午 10 点到上午 11 点有多少个对象,比如上午 11 点到下午 12 点等。那么我如何使用 Java 8 Stream API 来实现它。
最佳答案
试试这个:
Map<Integer, List<MyObject>> result = list.stream()
.collect(Collectors.groupingBy(o -> Instant.ofEpochMilli(o.getTime())
.atZone(ZoneOffset.UTC).getHour()));
result.forEach((hour, objects) ->
System.out.println(hour + " - " + (hour + 1) + ": " + objects));
这使用 Java Time API 来获取该时间戳的小时数。更改时区以满足您的需要。
关于java - 根据小时对数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56756542/