1.BeanUtils.copyProperties
BeanUtils.copyProperties(wrongBook, vo)
是 Spring 框架提供的一个工具方法,用于将一个 Java 对象的属性值复制到另一个 Java 对象。这在 DTO(数据传输对象)和实体类之间的转换中非常常用。
// 源类(数据库实体)
class WrongBook {
private String id;
private String questionId;
private String studentAnswer;
private boolean isCorrect;
// getters/setters
}
// 目标类(VO - 视图对象)
class WrongBookVO {
private String id;
private String questionId;
private String studentAnswer;
private boolean isCorrect;
private WringQuestionVo questionVo; // 额外属性
// getters/setters
}
使用 BeanUtils 复制属性:
WrongBook source = new WrongBook();
source.setId("1");
source.setQuestionId("Q1001");
source.setStudentAnswer("A");
source.setCorrect(true);
WrongBookVO target = new WrongBookVO();
BeanUtils.copyProperties(source, target);
// 结果:
// target.getId() → "1"
// target.getQuestionId() → "Q1001"
// target.getStudentAnswer() → "A"
// target.isCorrect() → true
// target.getQuestionVo() → null(源对象没有该属性,保持默认值)
注意事项
- 属性名必须相同:如果
source
有questionId
,而target
是qId
,则不会复制。 - 类型需兼容:
int
和Integer
可兼容,但String
和Integer
不可。 - 复杂类型:只复制基本类型和嵌套对象的引用,不会递归复制。
2.questionList.stream()
将题目ID映射到题目对象(用于快速查找) Map<String, Question> questionMap = questionList.stream() .collect(Collectors.toMap(Question::getId, q -> q));
把questionList,按quesiton里面的id写成map的形式!
3.getRecords().stream()
List<String> questionIds = wrongBooksPage.getRecords().stream() .map(WrongBooks::getQuestionId) .filter(Objects::nonNull) .collect(Collectors.toList());
提取wrongBooksPage集合里面的某一个字段成list集合,这里提取的是id