2

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?

2 Answers 2

6

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(";")

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, its worth noting when iterating over any collection asSequence transforms it into a Sequence and is lazily collected on the terminal result, rather than just collection which eagerly collects on every transformation or operater. Seqience in many respects is akin to the Java stream api.
4

First, you need to filter your list. And then you can use joinToString method.

val result : String = data.filter { it.state }.joinToString(seperator = ";") { it.string }

After that you can convert the string to list of strings like this :

val list = result.split(";")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.