Home > database >  How can I convert a StringBuilder item in a List of strings in Android Studio using Kotlin?
How can I convert a StringBuilder item in a List of strings in Android Studio using Kotlin?

Time:12-14

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:

  1. take the StringBuilder and convert it to a list (not recommended)
val list1 = myStringBuilder.toString().trim('\n').split("\n")
  1. 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)
}

  1. Use the fold function
val list3 = responseData.fold(ArrayList<String>()) { list, value ->
    list.add(value.hospitalName)
    list
}
  • Related