1

I want to take certain element from a collection to create another one.

Example I have a list created from this object

Student (Id, Code, FirstName, LastName, Age, Birthday)` 

and I want to create a new collection from my first one that contains certain fields example

NewStudent(FirstName, LastName, Age)

I tried using map, filter but I can't get the result right.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Noah13
  • 337
  • 4
  • 13

2 Answers2

4

map works fine for this scenario:

data class Student(val id: Int, val code: String, val firstName: String, val lastName: String, val age: Int, val birthday: String)
data class NewStudent(val firstName: String, val lastName: String, val age: Int)

val students = listOf(
   Student(1, "A", "1F", "1L", 11, "1/1/2000"), 
   Student(2, "B", "2F", "2L", 12, "1/2/2000"),
   Student(3, "C", "3F", "3L", 13, "1/3/2000")
)

val newStudents = students.map { student -> 
    NewStudent(student.firstName, student.lastName, student.age) 
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
kabuko
  • 36,028
  • 10
  • 80
  • 93
  • I didn't know we could use it that way more than two hours I try different solution ! thank you ! – Noah13 Jan 11 '18 at 00:16
2

I agree with kabuko but would like to add an alternative usage of map:

It's possible to destructure objects (of data classes e.g.) even inside a lambda, such as the one passed to map:

val newStudents = students.map { (_, _, fn, ln, age, _) ->
    NewStudent(fn, ln, age)
}

The underscores indicate the properties that are irrelevant for the mapping. This is a more readable solution imho.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • Not all objects can be destructured. Only instances of a data class or instances of other classes which implement componentN(). Otherwise good point. – Willi Mentzel Jan 15 '18 at 21:31
  • Good point, I took it for granted that he’s using data classes. Thank you. – s1m0nw1 Jan 15 '18 at 21:36