Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select property from each object in a list

Say I have a List<Tuple>, where the first element in each is a string. Is there an extension function in Kotlin to select the first element from each of these tuples?

I'm looking for something like the C# LINQ syntax for Select:

myTuples.Select(t => t.item1)
like image 576
Nate Jenson Avatar asked Sep 12 '17 15:09

Nate Jenson


1 Answers

In Kotlin, a Tuple could be a Pair or a Triple. You could just map over the list and select out the first element, like this:

val myTuples : List<Triple<String,String,String>> = listOf(
    Triple("A", "B", "C"), 
    Triple("D", "E", "F")
)
val myFirstElements: List<String> = myTuples.map { it.first } // ["A", "D"]

And of course, you can leave off the types, I've left them in to make this easier to follow.

like image 99
Todd Avatar answered Oct 21 '22 15:10

Todd