Kotlin distinct() from 2 Dimensional array

fun main() {

    val Data = ArrayList<List<String>>()
    
    Data.add(listOf("32701", "First"))
    Data.add(listOf("32702", "Second"))
    Data.add(listOf("32702", "Second"))
    Data.add(listOf("32701", "First True"))
    
    println(Data.distinct())

}

Result :

[[32701, First], [32702, Second], [32701, First True]]

Question How about removing data [32701, First] and get new data with the same value ?

Expected :

[32702, Second], [32701, First True]]

Use Pair<String, String> instead of List<String> and distinctBy{it.first}.

1 Like

Hi, i have try with that

import java.net.URI

fun main() {

    val DistributorNotes = ArrayList<Pair<String, String>>()
    
    DistributorNotes.add(Pair("32701", "First"))
    DistributorNotes.add(Pair("32702", "Second"))
    DistributorNotes.add(Pair("32702", "Second"))
    DistributorNotes.add(Pair("32701", "First Second"))
    
    println(DistributorNotes.distinctBy { it.first } )

}

But the result is : [(32701, First), (32702, Second)] how to keep the “latest” 32701 ? So the result is [32702, Second], [32701, First True]]

This is how distinct works. It choses the first occurrence with the given feature. If you want the last you need some kind of custom logic. I think that the easiest way is to just reverse your list:
distributorNotes.asReversed().distinctBy{it.first}.

Please note the code style. In Kotlin variables usually start with a small letter.

3 Likes