I have this StringBuilder item in my retrofit :
retrofitData.enqueue(object:Callback<List<HospitalResponse>?>{
override fun onResponse(call: Call<List<HospitalResponse>?>, response: Response<List<HospitalResponse>?>) {
val responseData = response.body()!!
val myStringBuilder = StringBuilder()
for(hospitalResponse in responseData){
myStringBuilder.append(hospitalResponse.hospitalName)
myStringBuilder.append("\n")
}
and I want to convert the StringBuilder to a list :
val hospitals = mutableListOf<String>()
How can I do that ?
CodePudding user response:
I see three options:
- take the StringBuilder and convert it to a list (not recommended)
val list1 = myStringBuilder.toString().trim('\n').split("\n")
- create a list and put the names into the list instead of appending it to the StringBuilder
val list2 = ArrayList<String>()
for(hospitalResponse in responseData){
list2.add(hospitalResponse.hospitalName)
}
- Use the fold function
val list3 = responseData.fold(ArrayList<String>()) { list, value ->
list.add(value.hospitalName)
list
}