Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string array in Kotlin from data class

Tags:

android

kotlin

I have a data Class like

data class Data(val string: String, val state: Boolean)

and that class is an array like

val data = ArrayList<Data>()
data.add(Data("String 1", false)
data.add(Data("String 2", true)
data.add(Data("String 3", true)
data.add(Data("String 4", false)

I need to concatenate only true strings like

val result = "String 2;String 3"

I took a look at joinToString() method, but no idea how to deal with in this case. One more thing is that, I need to get those concatenated strings later back as Array.

How optimal achieve that?

like image 253
Mark Delphi Avatar asked Mar 24 '26 21:03

Mark Delphi


1 Answers

Something as simple as this :

        val result = data.asSequence()
           .filter(Data::state)
           .map(Data::string)
           .joinToString(separator = ";")

Result :

String 2;String 3

Then :

result.split(";")

like image 91
Mark Avatar answered Mar 27 '26 09:03

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!