I have a forloop and inside it I need to create a custom object , set some values in it with some conditions and then create list of those custom object. I am not getting how we can do it in a nice way. I have done it in this way.
List<Response> responseData = new ArrayList<>();
ArrayList<Items> items = response.getItems();
for (Items item : items) {
Response response= new Response();
response.setId(item.getId());
if (!item.getPId().isEmpty() && !item.getOId().isEmpty()) {
response.setPId(item.getPId());
response.setOd(item.getOId());
} else if (!item.getPId().isEmpty() && item.getErID().isEmpty()) {
response.setPId(item.getPId());
}else if(!item.getErID().isEmpty()){
// log error
}
responseData .add(response);
}
how can I remove these if else conditions and create list of custom object Response.
CodePudding user response:
According to your code, you are setting values in response and isEmpty() needs to be checked before setting the values in response. here, we can simply check the empty condition seperately for each variable to set. You can also pull out the code inside for loop to a seperate method to set all the values in response. Below is my one of the implementation:
List<Response> responseData = new ArrayList<>();
ArrayList<Items> items = response.getItems();
for (Items item : items) {
Response response= new Response();
response.setId(item.getId());
if (!item.getPId().isEmpty()){
response.setPId(item.getPId());
}
if( !item.getOId().isEmpty()){
response.setOd(item.getOId());
}
if(!item.getErID().isEmpty()){
// log error
}
responseData.add(response);
}
Hope this will be helpful.
CodePudding user response:
You can use a Java
Stream like this by changing your constructor and map your values:
List<Response> responses = items.stream()
.map(item -> new Response(item.getPid(), item.getOid()))
.collect(Collectors.toList());