1

In service class of a REST API, I am receiving a list of roll no and mobile no. I am fetching student details by sending roll no. from repository. For each student I want to update mobile no corresponding to the roll no in the sequence I received.

Service class

public List<Student> updateContactNoOfStudents (List<Long> rollNo, List<String> ContactNo)
{
  List <Student> studentList = new ArrayList<>();
  try{
     studentList.add(studentRepository.fetchStudentListForUpdatingContactNo(rollNo));
     
     studentList.forEach((student->{ 
     student.setContactNo(contactNo.get(0));
     studentRepository.storeStudent(student);
     }));
 }catch (StudentException StudentException){
   Logger.error("Updation of Contact No Failed : {}",studentException);
}
return studentList;

}

Above code is not working as expected, What change shall I do, so that. For each student contact no gets updated in the sequence I received for corresponding roll No.

Controller class

@PostMapping (value = "/updateContactNo/")
public ResponseEntity <List<Student>> FetchingStudentForUpdatingContactNo (@RequestBody StudentUpdateDto studentupdateDto){
 try{
    return ResponseREntity.ok().body(studentService.updateContactNoOfStudents(studentUpdatDto.getRollNo(), studentUpdatDto.getContactNo()));
}catch (Exception e){
 throw new StudentException("Exception  in fetching Student List for updating contact no",e);
}
}
2
  • Does studentRepository.fetchStudentListForUpdatingContactNo(rollNo) method takes a list to fetch the records? Can you share your repository method decalaration. Commented Jan 13, 2022 at 8:20
  • @GovilKumar Yes, for each roll no, it fetch particular student detail. I am sending list of roll numbers. Commented Jan 13, 2022 at 8:23

1 Answer 1

1

You can use stream:

studentList.stream().map(student->{ 
     int indexOfStudent = studentList.indexOf(student);
     student.setContactNo(contactNo.get(indexOfStudent));
     studentRepository.storeStudent(student);
     return student;
     });
Sign up to request clarification or add additional context in comments.

2 Comments

@Souchail_HARRATI thank you so much, but for each student it will update same contact no (contactNo.get(0)) which is at index 0. For each student there is different contact no in the list. How to change conatact no for each student
you can use index of student: student.setContactNo(contactNo.get(studentList.indexOf(student));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.