将响应存储在变量中



我试图在Builder中存储对Arrays.asList的每个响应,但它不起作用。我尝试了很多,但没有成功。怎么做?这是我第一次将响应存储在单个变量中。

将响应存储在Builder中的Arrays.asList中只是一个测试。请建议最好的方法。

//model entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Student{
private String firstname;
private String lastname;
private String age;
}

//model entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class StudentResponse{
private List<String> responsefirstname;
private List<String> responselastname;
private List<String> responseage;
public static StudentResponse convertToResponse(List<Student> student){
return StudentResponse.builder()
.responsefirstname(Arrays.asList(student.get(0).getFirstname))
.responselastname(Arrays.asList(student.get(0).getLastname))
.responseage(Arrays.asList(student.get(0).getAge))
.build();
}
}

//Service
public class StudentService{
@Autowired
private StudentRepo repo;
public StudentResponse findStudent(String sfirstname){
List<Student> students =  repo.findByFirstname(sfirstname);
List<StudentResponse> studentResponse = students.stream
//   .map(StudentResponse::convertToResponse) //dont work
.collect(Collectors.toList());
return studentResponse
}
}

预期响应必须像这个

{
"firstname":["justin","ana","marie"],
"lastname": ["last1","last2","las3"],
"age": [45,55,28]
}

不是像这个那样的倍数

{
"firstname":"justin",
"lastname": "last2",
"age": 55
},
{
"firstname":"justin",
"lastname": "last1",
"age": 45
}

只需在学生列表上循环:

public static StudentResponse convertToResponse(List<Student> students) {
List<String> firstNames = new ArrayList<>(students.size());
List<String> lastNames = new ArrayList<>(students.size());
List<Integer> ages = new ArrayList<>(students.size());
for (Student student : students) {
firstNames.add(student.getFirstName());
lastNames.add(student.getLastNames());
ages.add(student.getAge());
}
return StudentResponse.builder()
.responsefirstname(firstNames)
.responselastname(lastNames)
.responseage(ages)
.build();
}

相关内容

  • 没有找到相关文章

最新更新