一、背景
1)问题描述
假如存在对象数组A,包含一些属性,现在需要给A加一些属性,并输出对象数组B,涉及到两个知识点:①需要把A的对象挨个增加新的属性②输出B,则需要把A的属性都复制到B
2)举个栗子
有list对象数组A,有属性userId和model,现在需要输出对象数组B,数组B中包含所有A中的对象,但需要多一个属性name
二、解决办法
①把A的属性复制过来
不能使用set方法一个一个复制,可以直接复制对象
BeanUtils.copyProperties(a, b);
②循环给B中的每个对象赋值name值
不能使用for循环遍历A里面的所有对象,那是java7的用法,java8用 stream().map.collect就可以了
List<B> listB = aList.stream().map(t->{
B b = new B();
String name;
name = "XXXX";
BeanUtils.copyProperties(a, b);
b.setName(name);
return b;
}).collect(Collectors.toList());
我自己的源码
public List<MobileList> queryMobile(){
List<MobileInfo> mobileInfoList = mobileInfoMapper.queryMobileAll();
List<MobileList> mobileLists= mobileInfoList.stream().map(t->{
MobileList mobileList = new MobileList();
String name;
name = userInfoMapper.queryNameByUserId(t.getOwner());
BeanUtils.copyProperties(t, mobileList);
mobileList.setName(name);
return mobileList;
}).collect(Collectors.toList());
return mobileLists;
}
三、问题
第一次输出mobileLists时候居然都是重复一模一样的数据
四、问题原因
因为stream().map.collect方法用的不对,MobileList mobileList = new MobileList();最新的对象应该在循环体内创建,而我之前是在循环体外创建的,导致循环输出了最后一个对象。