You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java8将员工按BookId分组为Map集合?

按BookId分组员工的Java 8实现方案

要实现将拥有相同BookId的员工分组,核心是先将每个员工与他持有的每一个BookId建立关联(扁平化处理),再通过分组收集结果。直接用Collectors.groupingBy无法完成是因为每个员工对应多本书,需要先拆分映射关系。

核心实现代码

首先是DTO的基础定义(确保Getter方法可用):

class Employee {
    private List<Book> bookList;
    // 其他属性、构造方法省略
    public List<Book> getBookList() {
        return bookList;
    }
}

class Book {
    private Long bookId;
    private String bookName;
    // 其他属性、构造方法省略
    public Long getBookId() {
        return bookId;
    }
}

然后是分组逻辑:

// 从employeeList生成按BookId分组的员工列表Map
Map<Long, List<Employee>> employeeGroupedByBookId = employeeList.stream()
    // 扁平化:将每个员工拆分为【BookId-员工】的映射条目
    .flatMap(employee -> employee.getBookList().stream()
        .map(book -> new AbstractMap.SimpleEntry<>(book.getBookId(), employee)))
    // 按BookId分组,收集对应的员工列表
    .collect(Collectors.groupingBy(
        AbstractMap.SimpleEntry::getKey,
        Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList())
    ));

可选优化:去重处理

如果存在同一个员工持有同一BookId多次的情况,可以在扁平化后加入distinct()避免重复统计:

Map<Long, List<Employee>> employeeGroupedByBookId = employeeList.stream()
    .flatMap(employee -> employee.getBookList().stream()
        .map(book -> new AbstractMap.SimpleEntry<>(book.getBookId(), employee))
        .distinct()) // 去重同一员工与同一BookId的重复关联
    .collect(Collectors.groupingBy(
        AbstractMap.SimpleEntry::getKey,
        Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList())
    ));

内容的提问来源于stack exchange,提问作者chand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:31:02