需求:已知对象1中的数值和对象2中的数值,对象1中的id和对象2中的favoId是相同的,想把对象1和2数据整合到一起,
我们就新建一个对象All,字段包含对象1和2,把对象1和2都放入到all对象中,可以用到BeanUtils.copyProperties进行对象赋值。若是字段很少,可以用set,get,若是很多字段,实现起来就很麻烦。
BeanUtils.copyProperties(源对象,目标对象)
示例:
对象1
package com.c3stones.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/**
* 学生实体
* @author CL
*/
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Test1 {
private Integer id;
private String name;
private String icon;
}
对象2
package com.c3stones.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 学生实体
* @author CL
*/
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Test2 {
private Integer favoId;
private String online;
private String status;
}
对象all
package com.c3stones.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/**
* 学生实体
*
* @author CL
*
*/
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TestAll {
private Integer id;
private String name;
private String icon;
/**
* 新增的Test2的字段
*/
private String online;
private String status;
}
把对象1和2整合起来
package com.c3stones.controller;
import com.c3stones.entity.Test1;
import com.c3stones.entity.Test2;
import com.c3stones.entity.TestAll;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 需求:已知对象1中的数值和对象2中的数值,对象1中的id和对象2中的coinId是相同的,想把对象1和2数据整合到一起
* 我们就新建一个对象All,字段包含对象1和2,把对象1和2都放入到all对象中,可以用到BeanUtils.copyProperties进行对象赋值
*/
public class Test {
public static void main(String[] args) {
System.out.println(show());
}
public static List<TestAll> show(){
List<Test1> list1 = new ArrayList<>();
List<Test2> list2 = new ArrayList<>();
list1.add(new Test1(1,"张三","F"));
list1.add(new Test1(2,"李四","F"));
list1.add(new Test1(3,"王五","W"));
list2.add(new Test2(1,"在线","打游戏"));
list2.add(new Test2(2,"下线","看书"));
List<TestAll> listAll = list1.stream().map(s ->{
TestAll testAll = new TestAll();
BeanUtils.copyProperties(s,testAll);
Test2 test2 = list2.stream().filter(l2 -> l2.getFavoId().equals(s.getId())).findFirst().orElse(null);
testAll.setOnline(test2 != null ? test2.getOnline() : "");
testAll.setStatus(test2 != null ? test2.getStatus() : "");
return testAll;
}).collect(Collectors.toList());
return listAll;
}
}
注意:
输出结果:
[TestAll(id=1, name=张三, icon=F, online=在线, status=打游戏), TestAll(id=2, name=李四, icon=F, online=下线, status=看书), TestAll(id=3, name=王五, icon=W, online=, status=)]