Alexei
Alexei

Reputation: 15646

Transform list of one items type to list of another items type

Android Studio 3.6

Snippet:

private fun createHistoryList(participantsEffectResourceList: List<ParticipantsEffectResource>) {
        val historyList = mutableListOf<MyHistoryItem>()
        participantsEffectResourceList.forEach({
            val date = it.operation.appliedAt
            val details = it.operation.details
            val myHistoryItem = MyHistoryItem(date, details)
            historyList.add(myHistoryItem)
        })
    }

As you can see I extract property from one item type (ParticipantsEffectResource) and transform it to another list of items (MyHistoryItem).

Nice. It's work fine.

But can any another simpler method? E.g. by participantsEffectResourceList.map {} or smt else?

Upvotes: 0

Views: 28

Answers (1)

some user
some user

Reputation: 1775

List already provides .map() you can use:

fun createHistoryList(participantsEffectResourceList: List < ParticipantsEffectResource > ) {
    val historyList = participantsEffectResourceList.map {
         MyHistoryItem(it.operation.appliedAt, it.operation.details)
     }
}

Upvotes: 1

Related Questions