Grouping by object value, counting and then setting group key by maximum object attribute

前端 未结 4 959
误落风尘
误落风尘 2020-11-28 14:53

I have managed to write a solution using Java 8 Streams API that first groups a list of object Route by its value and then counts the number of objects in each group. It ret

4条回答
  •  隐瞒了意图╮
    2020-11-28 15:31

    Here's one approach. First group into lists and then process the lists into the values you actually want:

    import static java.util.Comparator.comparingLong;
    import static java.util.stream.Collectors.groupingBy;
    import static java.util.stream.Collectors.toMap;
    
    
    Map routeCounts = routes.stream()
            .collect(groupingBy(x -> x))
            .values().stream()
            .collect(toMap(
                lst -> lst.stream().max(comparingLong(Route::getLastUpdated)).get(),
                List::size
            ));
    

提交回复
热议问题