背景:现在有一个字段非常多大实体类1构成的集合一,另一个集二合中的实体类2需要集合一中的部分属性,所以需要进行属性的复制。
基础类一:作为复制的源头
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name; // 姓名
private Integer salary; // 薪资
private Integer age; // 年龄
private String sex; //性别
private String area; // 地区
}
基础类二:作为输出源
import lombok.Data;
@Data
public class Son {
private String name;
private Integer age;
}
实现一
@Test
public void copyEntity() throws Exception {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
personList.add(new Person("Anni", 8200, 24, "female", "New York"));
personList.add(new Person("Owen", 9500, 25, "male", "New York"));
personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
List<Son> sonList = personList.stream().map(person -> {
Son son = new Son();
try {
BeanUtils.copyProperties(son,person);
/*son.setName(person.getName());
son.setAge(person.getAge());*/
} catch (Exception e) {
e.printStackTrace();
}
return son;
}).collect(Collectors.toList());
sonList.forEach(System.out::println);
}
实现二
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
public class CopyEntity {
/**
* @param input 输入集合
* @param clzz 输出集合类型
* @param <E> 输入集合类型
* @param <T> 输出集合类型
* @return 返回集合
*/
public static <E, T> List<T> convertList2List(List<E> input, Class<T> clzz) {
List<T> output = Lists.newArrayList();
if (!CollectionUtils.isEmpty(input)) {
for (E source : input) {
T target = BeanUtils.instantiate(clzz);
BeanUtils.copyProperties(source, target);
output.add(target);
}
}
return output;
}
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
personList.add(new Person("Anni", 8200, 24, "female", "New York"));
personList.add(new Person("Owen", 9500, 25, "male", "New York"));
personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
List<Son> sons = CopyEntity.convertList2List( personList,Son.class);
sons.forEach(System.out::println);
}
}
注意:实现一和实现二所使用的是jar包不同,导致的影响是BeanUtils.copyProperties()该方法参数的位置不同。
第一个实现所用到的jar包:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
第二个实现所用到的jar包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.8</version>
<scope>compile</scope>
</dependency>
本文介绍如何将一个包含大量属性的实体类集合复制到另一个实体类集合中,只保留部分属性。主要探讨了两种不同的实现方式,这两种方式使用的jar包不同,导致方法参数位置的差异。

1846

被折叠的 条评论
为什么被折叠?



