i'm an newer to kotlin.
I Have a data class called User with three properties name, age and city. And I have a list of
array. I want to map this list of array User to obtain a new list containing the name and the city of the user.
these my code
data class User(var name: String, var age: Int, var city: String)
fun main(args: Array<String>) {
val user1 = User("John", 18, "Paris")
val user2 = User("Sara", 25, "Tokyo")
val user3 = User("Dave", 34, "Tunis")
val listOfArrayUser = arrayListOf<User>()
listOfArrayUser.addAll(listOf(user1, user2, user3))
var myNewList : List<String> = listOfArrayUser.stream().map { ("${it.name}-${it.city}") }.toList()
println( "My new list : " )
println( myNewList)
}
But i doesn't have the correcdt result. How can i do this please
CodePudding user response:
(This answer applies to revision #1 of the question only)
You have a nested collection of users, so you need to map
twice. To avoid ending up with a List<List<String>>
, Kotlin offers a flatMap
method.
Note that stream()
is from the Java world and not needed in Kotlin. You also don't need to have an args
parameter in your main method and the toList()
after the mapping is superfluous as well.
Here is a fixed version of your code:
data class User(var name: String, var age: Int, var city: String)
fun main() {
val user1 = User("John", 18, "Paris")
val user2 = User("Sara", 25, "Tokyo")
val user3 = User("Dave", 34, "Tunis")
var listOfArrayUser = listOf<Array<User>>(arrayOf(user1, user2, user3))
var myNewList : List<String> = listOfArrayUser.flatMap { it.map { "${it.name}-${it.city}" } }
println("My new list : ")
println(myNewList)
}
Output:
My new list :
[John-Paris, Sara-Tokyo, Dave-Tunis]
As an additional note: data classes are usually intended to be immutable, so your User
class should probably look like this (note the val
instead of var
):
data class User(val name: String, val age: Int, val city: String)
CodePudding user response:
I'm not sure why you would want to use a stream for that. You can do
var myNewList : List<String> = listOfArrayUser.flatMap { it.toList() }.map { ("${it.name}-${it.city}") }