15

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)
Nate Jenson
  • 2,664
  • 1
  • 25
  • 34

1 Answers1

21

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.

Todd
  • 30,472
  • 11
  • 81
  • 89