【问题标题】:Java 8 groupingBy: Simple Grouping by a Single ColumnJava 8 groupingBy:按单列进行简单分组
【发布时间】:2021-01-16 23:24:10
【问题描述】:

我想使用 Java 8 groupingBy Collector 按单列进行简单的分组,所以我这样做了:

Map<IUser, List<IUserPost>> postsPerUser =
                autorisationUsersRepository.findById(dateReference)
                .stream()
                .map(UsersMapper::map) -> Stream<IUser>
                .map(IUser::getPosts)  -> Stream<List<IUserPost>>
                .collect(groupingBy(IUserPost::getUser));

但是我有这个编译错误:

Required type:
Collector
<? super List<IUserPost>,
A,
R>
Provided:
Collector
<IUserPost,
capture of ?,
Map<IUser, List<IUserPost>>>
reason: no instance(s) of type variable(s) exist so that List<IUserPost> conforms to IUserPost

【问题讨论】:

    标签: java lambda group-by java-8 collectors


    【解决方案1】:

    嗯,List&lt;IUserPost&gt;不是IUserPost,所以你可以这样分组。

    您可以使用Collectors.toMap() 直接收集到地图,将键(用户)映射到自身,并将值映射到他们的帖子列表:

    postsPerUser =
        autorisationUsersRepository.findById(dateReference).stream()
        .map(UsersMapper::map) // Stream<IUser>
        .collect(toMap(user -> user, IUser::getPosts)) // Map<IUser, List<IUserPost>>
    

    或者您可以使用flatMap 获取Stream&lt;IUserPost&gt;,然后您可以按用户分组。

    postsPerUser =
        autorisationUsersRepository.findById(dateReference).stream()
        .map(UsersMapper::map) // Stream<IUser>
        .flatMap(IUser::getPosts) // Stream<IUserPost>    
        .collect(groupingBy(IUserPost::getUser)) // Map<IUser, List<IUserPost>>
    

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2017-12-24
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 2017-07-30
      • 1970-01-01
      相关资源
      最近更新 更多