如何在流(java)中添加dateTime值?

时间:2017-05-20 14:13:30

标签: java lambda java-8 java-stream

今天我开始学习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.  ... 

}

}

我不知道如何获得这个结果:(。我尝试了不同的方法,我无法知道如何获得每项活动的总持续时间...谢谢你的帮助!

2 个答案:

答案 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)

java-8 Duration与joda Duration不同。怎么样:

Map<String, Duration> durations = list.stream().collect(Collectors.toMap(
        it -> it.activityLabel,
        it -> new Duration(it.startTime, it.endTime),
        Duration::plus
));