Filtering a list with elements contained in another list

Asked

Viewed 42 times

2

I have the class

class estruturaPosicaoXY(val x: Float, val y: Float) {}

then fill out a list of that class

through the method:

fun mapearXY(x: Float, y: Float): List<estruturaPosicaoXY> {
        val posicoes = mutableListOf<estruturaPosicaoXY>()

        posicoes.add(estruturaPosicaoXY(x, y))
        if (x - 1 >= 0 && y - 1 >= 0)
            posicoes.add(estruturaPosicaoXY(x - 1, y - 1))
        if (x - 2 >= 0 && y - 2 >= 0)
            posicoes.add(estruturaPosicaoXY(x - 2, y - 2))
        posicoes.add(estruturaPosicaoXY(x + 1, y + 1))
        posicoes.add(estruturaPosicaoXY(x + 2, y + 2))
        posicoes.add(estruturaPosicaoXY(x + 3, y + 3))
        posicoes.add(estruturaPosicaoXY(x + 4, y + 4))
        posicoes.add(estruturaPosicaoXY(x + 5, y + 5))

        return posicoes
    }

I fill that list with the method above

val posicoesMapeadas = mapearXY(100, 100)

I need to use this list to filter another list

val estruturasFilhas =
                    estruturas.filter { it.x == /**/ && it.y ==/**/}

How can I use list posicoesMapeadas to filter the list estruturas to return an object where the x and y of estruturas is equal to x and y of some item of posicoesMapeadas? In c# for example, I can easily do this with the method .Contains, but I couldn’t find anything like it on Kotlin.

1 answer

1


I believe this example solves what you need. I made some adaptations to make it more didactic. I mean, I understood the result is a list only with the corresponding elements.

Can rotate in the Kotlin playground to test and check if this is the case. I only modified the class name because it seems to represent an X,Y point

data class Point(var x: Int, var y: Int) {}

fun main(){
    
    
    val listaA = ArrayList<Point>()
    listaA.add(Point(100,100))
    listaA.add(Point(200,200))
    listaA.add(Point(300,300))
    
    val listaB = ArrayList<Point>()
    listaB.add(Point(200,200))
    listaB.add(Point(500,500))
    

    val listaResultado = listaB.flatMap { 
        p -> listaA.filter { p.x == it.x && p.y == it.y}
    }
    
    print(listaResultado.toString())
    
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.