How to add dateTime values in a stream(java)?

后端 未结 2 1572
夕颜
夕颜 2021-01-16 08:13

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

相关标签:
2条回答
  • 2021-01-16 08:36

    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
            )
        ));
    
    0 讨论(0)
  • 2021-01-16 08:49

    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
    ));
    
    0 讨论(0)
提交回复
热议问题