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

如何使用Java Stream将Car对象Set转换为扁平化的CarFlattened Set

Java Stream实现Car集合到CarFlattened集合的扁平化转换

需求说明

现有一个包含Car对象的Set,Car类包含两个属性:int carId、Set<Long> carSN,源数据如下:

1, [123, 789]
2, [456]
3, [123]

需要将其转换为包含CarFlattened对象的Set,CarFlattened类包含两个属性:int carId、Long carSN,转换后数据如下:

1, 123
2, 456
3, 123
1, 789

最简实现代码

首先定义Car和CarFlattened类(需确保CarFlattened实现equals和hashCode以支持Set去重):

import java.util.Objects;
import java.util.Set;

class Car {
    private int carId;
    private Set<Long> carSN;

    public Car(int carId, Set<Long> carSN) {
        this.carId = carId;
        this.carSN = carSN;
    }

    public int getCarId() { return carId; }
    public Set<Long> getCarSN() { return carSN; }
}

class CarFlattened {
    private int carId;
    private Long carSN;

    public CarFlattened(int carId, Long carSN) {
        this.carId = carId;
        this.carSN = carSN;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CarFlattened that = (CarFlattened) o;
        return carId == that.carId && Objects.equals(carSN, that.carSN);
    }

    @Override
    public int hashCode() {
        return Objects.hash(carId, carSN);
    }

    @Override
    public String toString() {
        return carId + ", " + carSN;
    }
}

核心转换逻辑使用Stream.flatMap实现扁平化映射:

import java.util.Set;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Set<Car> cars = Set.of(
            new Car(1, Set.of(123L, 789L)),
            new Car(2, Set.of(456L)),
            new Car(3, Set.of(123L))
        );

        Set<CarFlattened> flattenedCars = cars.stream()
            .flatMap(car -> car.getCarSN().stream()
                .map(sn -> new CarFlattened(car.getCarId(), sn))
            )
            .collect(Collectors.toSet());

        // 输出验证结果
        flattenedCars.forEach(System.out::println);
    }
}

代码说明

  • flatMap:将每个Car对象转换为一个由CarFlattened对象组成的流,再将所有子流合并为一个统一的流,实现集合的扁平化拆分
  • 内层map:将每个carSN元素与当前Car的carId组合,生成对应的CarFlattened对象
  • Collectors.toSet():将处理后的流收集为Set,依赖CarFlattened的equals和hashCode方法保证元素唯一性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:42:22