I am writing an API, which creates a list of User objects and then makes a call to a 3rd party webservice with that list. The 3rd party webservice then responds back with a list of UserDetails objects containing the details of the users. For ex:
Class User{
String id;
String name;
}
A list is constructed with the above User objects and then passed over to the 3rd party webservice.
List<User> users = new ArrayList <User>();
The 3rd party webservice then responds back with a list of UserDetails Objects.
Class UserDetails {
String id;
String email;
String accountNumber;
...
...
}
List<UserDetails> userDetails = new ArrayList <UserDetails>();
Now, to construct the response of my API, I construct a List of UserResponse objects which contains a mix of fields in User and UserDetails objects.
Class UserResponse{
String id;
String name;
String email;
String accountNumber;
....
...
}
To Construct this list of UserResponse objects, I have to iterate over user List and UserDetails List and then check if id's match and then construct the UserRepsonse Object and then add them to a list. The code is as below.
List <UserResponse> userResponseList = new ArrayList<UserResponse>();
for(User user : userRequest){
for(UserDetails userDetail: userDetails){
if(user.getid().equalsIgnoreCase(userDetail.getId())){
UserResponse userReponse = new UserResponse ();
userReponse.setId(user.getId());
userReponse.setName(user.getName());
userReponse.setEmail(userDetail.getEmail());
userReponse.setAccountNumber(userDetail.getAccountDetail());
userResponseList.add(userReponse);
}
}
}
And then return the userResponseList.
The above code works. But iterating over 2 lists is what is scaring me. My API can have about 200 users in 1 request. So I send a list of 200 user objects to 3rd party service and then the 3rd party webservice responds back with a list of 200 userDetails objects.
This means I will be iterating 200*200 items in the double iterator.
Is there an better and more efficient way to perform this logic instead of iterating this many times ?
Advance Thanks..
Aucun commentaire:
Enregistrer un commentaire