list<dto>转list<String>效果图
代码部分 List<SourceObject> sourceList = createSourceList(); List<String> collect = sourceList.stream().map(sourceObject -> sourceObject.getName()).collect(Collectors.toList()); collect.forEach(a->{ System.out.println(a); });
list<dto>转list<dto>效果图
代码部分
List<TargetObject> targetObjects = sourceList.stream().map(sourceObject -> TargetObject.builder().id(sourceObject.getId()).name(sourceObject.getName()).build()) .collect(Collectors.toList()); targetObjects.forEach(a->{ System.out.println(a); });
完整代码
package springboot; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author yourheart * @Description * @create 2024-05-10 16:49 */ public class ListToListTest { @Test public void test(){ List<SourceObject> sourceList = createSourceList(); List<String> collect = sourceList.stream().map(sourceObject -> sourceObject.getName()).collect(Collectors.toList()); collect.forEach(a->{ System.out.println(a); }); List<TargetObject> targetObjects = sourceList.stream().map(sourceObject -> TargetObject.builder().id(sourceObject.getId()).name(sourceObject.getName()).build()) .collect(Collectors.toList()); targetObjects.forEach(a->{ System.out.println(a); }); } private List<SourceObject> createSourceList() { // 创建一个简单的 SourceObject 列表 List<SourceObject> list = new ArrayList<>(); list.add(new SourceObject(1, "Apple")); list.add(new SourceObject(2, "Banana")); list.add(new SourceObject(3, "Orange")); return list; } } @Data class SourceObject { private int id; private String name; public SourceObject(int id, String name) { this.id = id; this.name = name; } // 省略构造函数和 getter/setter 方法 } @Data @Builder @NoArgsConstructor @AllArgsConstructor class TargetObject { private int id; private String name; // 省略构造函数和 getter/setter 方法 }
使用的依赖
<!--引入junit单元测试依赖--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.26</version> </dependency>
标签:基于,stream,list,List,sourceObject,collect,import From: https://www.cnblogs.com/q202105271618/p/18184957