Java 中将List<A>转List<B>

前提是 AB 两个对象的属性关系是A包含B的属性

List<A> listA =  // ... 初始化你的 A 列表
List<B> listB = new ArrayList<>();

// 转换逻辑
listB = listA.stream()
    .map(B::new)  // 等价于 .map(a -> new B(a))
    .collect(Collectors.toList());

B 类有一个构造函数,如下所示:

public class B {
    private String id;
    private String title;
    // 其他属性
    ...
    // 构造函数
    public B(A a) {
        this.id = a.getId();
        this.title = a.getTitle();
        // 根据 A 对象初始化其他属性
        ...
    }
}
posted @ 2025-01-21 09:36  笔兴洽谈室  阅读(44)  评论(0)    收藏  举报