Android Kotlin 如何删除列表中的重复值

Android Kotlin how to Remove duplicate values in a list

我正在尝试将 JSON 数据放入微调器中。

val product_sizes = productfeed.variants.joinToString { variants -> variants.option_values[0].name }
    Log.d("TAG", "TESTING:: ${product_sizes} ")

这是输出:

TESTING:: SMALL, MEDIUM, LARGE, 1 XL, 2 XL, 3 XL, SMALL, MEDIUM, LARGE, 1 XL, 2 XL, 3 XL, SMALL, MEDIUM, LARGE, 1 XL, 2 XL, 3 XL, SMALL, MEDIUM, LARGE, 1 XL, 2 XL, 3 XL, SMALL, MEDIUM, LARGE, 1 XL, 2 XL, 3 XL

我只想将一组尺寸放入微调器中,而不是其中的 5 个。 我也试过:

 val product_sizes = productfeed.variants.joinToString { variants -> variants.option_values[0].name.toSet().toList().toString() }
    Log.d("TAG", "TESTING:: ${product_sizes} ")

输出为:

TESTING:: [S, M, A, L], [M, E, D, I, U], [L, A, R, G, E], [1, , X, L], [2, , X, L], [3, , X, L], [S, M, A, L], [M, E, D, I, U], [L, A, R, G, E], [1, , X, L], [2, , X, L], [3, , X, L], [S, M, A, L], [M, E, D, I, U], [L, A, R, G, E], [1, , X, L], [2, , X, L], [3, , X, L], [S, M, A, L], [M, E, D, I, U], [L, A, R, G, E], [1, , X, L], [2, , X, L], [3, , X, L], [S, M, A, L], [M, E, D, I, U], [L, A, R, G, E], [1, , X, L], [2, , X, L], [3, , X, L]

请帮忙。谢谢!

您应该在加入之前将列表转换为 Set,而不是在

之后
val product_sizes = productfeed.variants
                               .map { it.option_values[0].name }
                               .toSet()
                               .joinToString()
Log.d("TAG", "TESTING:: ${product_sizes} ")

然后输出将是

TESTING:: SMALL, MEDIUM, LARGE, 1 XL, 2 XL, 3 XL

您还可以使用 distincBy 来省略 map 运算符。

val product_sizes = productfeed.variants
                               .distincBy { it.option_values[0].name }
                               .joinToString { it.option_values[0].name }
Log.d("TAG", "TESTING:: ${product_sizes} ")