今天我开始学习Java 8,所以我对Java 8很陌生。 我有一份活动清单。活动具有name,startTime,endTime。对于startTime和endTime,我正在使用joda时间的DateTime。
我正在尝试确定映射的Map(String,DateTime)形式的数据结构 对于每项活动,在监测期内计算的总持续时间。
以下是我的代码片段:
import java.util.ArrayList;
import java.util.Map;
import org.joda.time.DateTime;
class Activity {
public DateTime startTime;
public DateTime endTime;
public String activityLabel;
public Activity(DateTime startTime, DateTime endTime, String activityLabel) {
super();
this.startTime = startTime;
this.endTime = endTime;
this.activityLabel = activityLabel;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Activity> list = new ArrayList<>();
//adding activities to list
list.add(new Activity(new DateTime(2017, 5, 12, 13, 10, 0), new DateTime(2017, 5, 12, 13, 40, 0), "Showering"));
list.add(new Activity(new DateTime(2017, 5, 12, 13, 41, 0), new DateTime(2017, 5, 12, 14, 20, 0), "Cooking"));
list.add(new Activity(new DateTime(2017, 5, 12, 14, 20, 0), new DateTime(2017, 5, 12, 14, 50, 0), "Eating"));
list.add(new Activity(new DateTime(2017, 5, 12, 14, 51, 0), new DateTime(2017, 5, 12, 15, 30, 0), "Sleeping"));
list.add(new Activity(new DateTime(2017, 5, 12, 17, 22, 0), new DateTime(2017, 5, 12, 17, 30, 0), "Showering"));
list.add(new Activity(new DateTime(2017, 5, 12, 17, 41, 0), new DateTime(2017, 5, 12, 17, 50, 0), "Cooking"));
list.add(new Activity(new DateTime(2017, 5, 12, 17, 50, 0), new DateTime(2017, 5, 12, 18, 20, 0), "Eating"));
list.add(new Activity(new DateTime(2017, 5, 12, 18, 21, 0), new DateTime(2017, 5, 12, 20, 30, 0), "TV"));
//creating a stream from list
Map<String, DateTime> map;
// map = list.stream().collect(Collectors.groupingBy(s -> s.activityLabel, Collectors. ...
}
}
我不知道如何获得这个结果:(。我尝试了不同的方法,我无法知道如何获得每项活动的总持续时间...谢谢你的帮助!
答案 0 :(得分:3)
首先开始使用Java 8 DateTime API。有一个内置的Duration
类。然后你可以使用:
Map<String, Duration> map = list.stream().collect(
Collectors.groupingBy(a -> a.activityLabel,
Collectors.reducing(Duration.ZERO,
a -> Duration.between(a.startTime, a.endTime).abs(), Duration::plus
)
));
<强> 修改 强>
由于您要使用Joda
,因此可以使用Period
代替Duration
获得相同的结果:
Map<String, Period> map = list.stream().collect(
Collectors.groupingBy(a -> a.activityLabel,
Collectors.reducing(Period.ZERO,
a -> new Period(a.startTime, a.endTime), Period::plus
)
));
答案 1 :(得分:3)