Kotlin: Как получить списки от Arraylist? - PullRequest
0 голосов
/ 17 марта 2020

Вот простое ArrayList:

private val fruits = arrayListOf(
    FruitsInBox("Apple", "Korea", "2ea"),
    FruitsInBox("Mango", "India", "1ea"),
    FruitsInBox("Strawberry", "Australia", "1ea"),
    FruitsInBox("Kiwi", "NewZealand", "2ea"),
    FruitsInBox("Peach", "Korea", "3ea")
)

И я хочу отфильтровать данные по количеству фруктов, как показано ниже.

private var numberOfFruits = arrayOf("All", "1ea", "2ea", "3ea", "4ea")

Однако я надеюсь, поставить вещи "All", "1ea", "2ea", "3ea", "4ea" из ArrayList автоматически.

У вас есть идеи?

1 Ответ

3 голосов
/ 17 марта 2020

Вот пример того, как получить список третьих атрибутов FruitsInBox.

// definition of the class FruitsInBox
data class FruitsInBox(val name: String, val country: String, val quantity: String)

fun main(args: Array<String>) {
    // your example data
    val fruits = arrayListOf(
        FruitsInBox("Apple", "Korea", "2ea"),
        FruitsInBox("Mango", "India", "1ea"),
        FruitsInBox("Strawberry", "Australia", "1ea"),
        FruitsInBox("Kiwi", "NewZealand", "2ea"),
        FruitsInBox("Peach", "Korea", "3ea")
    )

    /*
     * since "All" is not a quantity derived from an instance of FruitsInBox,
     * you have to add it manually, so create a list containing only the String "All"
     */
    val allFruitQuantities = mutableListOf("All")

    // then get the distinct quantities sorted in a list
    val fruitQuantities = fruits.map { it -> it.quantity }
                                .distinct()
                                .sorted()
                                .toList()

    // add the sorted list of distinct values to the one containing "All"
    allFruitQuantities.addAll(fruitQuantities)

    // print the result
    println(allFruitQuantities)
}

Выход

[All, 1ea, 2ea, 3ea]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...