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

如何使用Java Stream按产品的类型列表分组生成Map

Java Stream 实现多类型分组解决方案

搜索关键词推荐

你可以使用以下关键词搜索相关问题:

  • Java Stream 多对多分组
  • Java Stream flatMap 分组
  • Java Stream 按集合元素分组

实现步骤与代码

首先需要确保Product类提供属性的访问方法(getter),否则无法在Stream中读取types和name:

class Product {
    private String name;
    private List<String> types;

    // 构造方法
    public Product(String name, List<String> types) {
        this.name = name;
        this.types = types;
    }

    // Getter方法
    public String getName() {
        return name;
    }

    public List<String> getTypes() {
        return types;
    }

    // 重写toString方便查看结果
    @Override
    public String toString() {
        return name;
    }
}

接下来通过Stream实现分组逻辑:

List<Product> products = new ArrayList<>();

List<String> type1 = new ArrayList<>();
type1.add("typeA");
type1.add("typeB");
products.add(new Product("product1", type1));

List<String> type2 = new ArrayList<>();
type2.add("typeB");
type2.add("typeC");
products.add(new Product("product2", type2));

List<String> type3 = new ArrayList<>();
type3.add("typeA");
type3.add("typeC");
products.add(new Product("product3", type3));

// 核心分组逻辑
Map<String, List<Product>> typeToProducts = products.stream()
    // 将每个Product拆分为(type, Product)的键值对,展开一对多关系
    .flatMap(product -> product.getTypes().stream()
        .map(type -> new AbstractMap.SimpleEntry<>(type, product)))
    // 按类型分组,收集对应的Product列表
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collectors.mapping(Map.Entry::getValue, Collectors.toList())
    ));

// 输出验证结果
typeToProducts.forEach((type, productList) -> {
    System.out.println(type + ": " + productList);
});

代码说明

  1. flatMap 展开关系:通过flatMap将每个Product与它的每个type进行配对,把原来的一对多结构拆分为多个(type, Product)的键值对,这是实现多类型分组的关键。
  2. groupingBy 分组收集:使用Collectors.groupingBy按type作为分组键,再通过Collectors.mapping将每个键对应的Product收集到列表中,最终得到目标结构的Map。

内容的提问来源于stack exchange,提问作者Đức Trường Đặng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:52:55