Avatar ·

如何从Kotlin数组中删除重复字符串:最佳方法

你好!我刚开始学习Kotlin,遇到了这样一个问题:我有一个字符串数组,其中包含很多重复元素。我需要获取一个只包含唯一值的新数组,同时保留首次出现的顺序。 以下是我的代码示例: ```kotlin fun main() { val fruits = arrayOf("apple", "banana", "apple", "orange", "banana", "grape", "apple") // 这里我想得到:["apple", "banana", "orange", "grape"] } ``` 我尝试过使用 `distinct()`,但它返回的是 `List`,而我需要的是数组。我还尝试过使用 `contains()` 进行循环检查,但这看起来很笨重,而且对于大型数组可能效率不高。 我当前的方法: ```kotlin fun removeDuplicates(arr: Array): Array { val result = mutableListOf() for (item in arr) { if (item !in result) { result.add(item) } } return result.toTypedArray() } ``` 这能工作,但