Today I started learning Java 8, so I\'m quite new to Java 8 and it\'s stuff. I have a list of activities. An activity has name, startTime, endTime. For startTime and endTi
First start to use Java 8 DateTime API. There is a built-in Duration
class. Then you can use:
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
)
));
EDIT
Since you've to use Joda
you can get the same results with (using Period
instead of 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
)
));
java-8 Duration is different with joda Duration. how about this:
Map<String, Duration> durations = list.stream().collect(Collectors.toMap(
it -> it.activityLabel,
it -> new Duration(it.startTime, it.endTime),
Duration::plus
));