Distraction
Distraction

Reputation: 460

kotlin list of Pair into list of Pair.first

I'm trying to get used to the idioms and shortcuts in Kotlin and I'm wondering if there was any way to do this.

val pairList = listOf(Pair(1, 2), Pair(5, 10), Pair(12, 15))
val firstList = // should be [1, 5, 12]

Or in general, any class with any one of their member variables. I currently have:

val pairList = listOf(Pair(1, 2), Pair(5, 10), Pair(12, 15))
val firstList = ArrayList<Int>()
pairList.forEach { firstList.add(it.first) }

Upvotes: 7

Views: 20356

Answers (1)

user8959091
user8959091

Reputation:

It is: val firstList = pairList.map { it.first }

first represents the 1st member of the pair, and of course there is second for the 2nd member

The same firstList be generalized for:

val pairList = listOf(Pair(ClassA(), ClassB()), Pair(ClassA(), ClassB()), Pair(ClassA(), ClassB()))

Upvotes: 14

Related Questions