- 示例代码
import com.alibaba.fastjson.JSON;
import com.example.demo.Demo.dto.Student;
import com.example.demo.pojo.StudentPlus;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class map {
public static void main(String[] args) {
Student stu1 = new Student();
stu1.setId(1);
stu1.setName("张三");
stu1.setDate(String.valueOf(new Date()));
Student stu2 = new Student();
stu2.setId(2);
stu2.setName("李四");
stu2.setDate(String.valueOf(new Date()));
//装载学生类
List<Student> stuList = new ArrayList<>();
Collections.addAll(stuList, stu1, stu2);
List<StudentPlus> plusList = new map().obj(stuList);
for (int i = plusList.size() - 1; i >= 0; i--) {
System.out.println("编号: " + i + ", 数据: " + JSON.toJSON(plusList.get(i)));
}
}
//聚合方法
private List<StudentPlus> obj(List<Student> stuList) {
return stuList.stream().map(this::conversion).collect(Collectors.toList());
}
//转换方法
private StudentPlus conversion(Student stu) {
StudentPlus studentPlus = new StudentPlus();
studentPlus.setId(stu.getId());
studentPlus.setName(stu.getName());
studentPlus.setDate(new Date(stu.getDate()));
return studentPlus;
}
//输出: 编号: 1, 数据: {"date":1626800157000,"name":"李四","id":2} 《----》 编号: 0, 数据: {"date":1626800157000,"name":"张三","id":1}
}