I have this data I want to get all employees with ...
# getting-started
z
I have this data I want to get all employees with permanent addresses, I want to even get one address for each employee 🤔
Copy code
val employees =
    listOf<Employee>(
        Employee(
            id = 1,
            listOf(
                Address(id = 1, isPerm = false),
                Address(id = 2, isPerm = true),
                Address(id = 3, isPerm = true)
            )
        ),
        Employee(
            id = 2,
            listOf(
                Address(id = 1, isPerm = false),
                Address(id = 2, isPerm = false),
                Address(id = 3, isPerm = true)
            )
        )
    )
m
what do you mean with the last part of your question? What should employee with
id = 1
return for you since he has two?
z
only one address, first address sorted by id
The first address
k
Copy code
val result = employees
    .filter { (_, addresses) -> addresses.any { it.isPerm } }
    .map { (id, addresses) -> id to addresses.first { it.isPerm } }
(This assumes the addresses in the list are already sorted by id. It returns a Pair of employee id to address, but you can instead create a new data class containing an Employee with a single address.)
z
Hmmm got it
m
Copy code
employees.mapNotNull { employee ->
    employee.addresses
        .firstOrNull(Address::isPerm)
        ?.let { employee to it }
}
per employee, grab the first Address with isPerm=true, if it exists, map it to a pair of employee to address
👍 2
y
Also if you don't want the address in a pair and you simply want just the employees you can do:
Copy code
employees.filter { it.addresses.any(Address::isPerm) }
👍 1