首先建两个实体类
第一个实体类
package com.app.service.studentTest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName StudentMasssge
* @Description TODO
* @Author houbing
* @Date 2023/7/14 13:24
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentMasssge {
private String name;
private String sex;
private Integer age;
private String address;
}
第二个实体类
package com.app.service.studentTest;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName Student
* @Description 实体
* @Author houbing
* @Date 2023/7/13 10:04
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student {
private String name;
private String sex;
private Integer age;
}
开始进行测试,这里我用了三种方法进行测试
package com.app.service.studentTest;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ClassName StudentTest1
* @Description list集合的对象类型转换为另一个对象类型
* @Author houbing
* @Date 2023/7/14 13:23
*/
public class StudentTest1 {
public static void main(String[] args) {
List<StudentMasssge> studentMasssgeList = new ArrayList<>();
studentMasssgeList.add(new StudentMasssge("zhangsan", "nan", 15, "xinyang"));
studentMasssgeList.add(new StudentMasssge("lisi", "nan", 17, "hebei"));
studentMasssgeList.add(new StudentMasssge("xieling", "nv", 18, "zhengzhou"));
studentMasssgeList.add(new StudentMasssge("wangwu", "nan", 16, "zhoukou"));
//方法一:用stream流中的map进行操作,此方法中被转成的对象类型类型要有@Builder这个注解
List<Student> collect = studentMasssgeList.stream().map(a -> Student.builder().name(a.getName())
.sex(a.getSex()).age(a.getAge()).build()).collect(Collectors.toList());
System.out.println("collect======"+collect);
//方法二:使用BeanUtils.copyProperties
List<Student> students = studentMasssgeList.stream().map(a -> {
Student student = new Student();
try {
//第一个参数要去复制的对象,第二个参数被复制的对象
BeanUtils.copyProperties(student, a);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return student;
}).collect(Collectors.toList());
System.out.println("students======"+students);
//方法三:使用for循环进行赋值
}
}
测试的结果如下