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

后端 未结 2 1575
夕颜
夕颜 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 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 map = list.stream().collect(
        Collectors.groupingBy(a -> a.activityLabel, 
            Collectors.reducing(Period.ZERO, 
                a -> new Period(a.startTime, a.endTime), Period::plus
            )
        ));
    

提交回复
热议问题