Kotlin - Idiomatic way to remove duplicate strings from array?

前端 未结 1 1704
傲寒
傲寒 2021-01-31 06:51

How to remove duplicates from an Array in kotlin?

1条回答
  •  别那么骄傲
    2021-01-31 07:19

    Use the distinct extension function:

    val a = arrayOf("a", "a", "b", "c", "c")
    val b = a.distinct() // ["a", "b", "c"]
    

    There's also distinctBy function that allows one to specify how to distinguish the items:

    val a = listOf("a", "b", "ab", "ba", "abc")
    val b = a.distinctBy { it.length } // ["a", "ab", "abc"]
    

    As @mfulton26 suggested, you can also use toSet, toMutableSet and, if you don't need the original ordering to be preserved, toHashSet. These functions produce a Set instead of a List and should be a little bit more efficient than distinct.


    You may find useful:

    • Kotlin idioms
    • What Java 8 Stream.collect equivalents are available in the standard Kotlin library?

    0 讨论(0)
提交回复
热议问题