0

Here is a simple 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")
)

And, I want to filter the data by the number of fruits, like below.

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

However, I hope to put the things "All", "1ea", "2ea", "3ea", "4ea" from the ArrayList, automatically.

Do you have any idea?

1
  • Can you shou us the class FruitsInBox? You have to map and filter by the attribute that holds those values. Commented Mar 17, 2020 at 8:37

1 Answer 1

3

Here's an example of how to get a list of the third attributes of the 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)
}

The output is

[All, 1ea, 2ea, 3ea]
Sign up to request clarification or add additional context in comments.

8 Comments

Cool! thanks mate! But, if I want to get the output without repetition, how can I do?
It's not really an id when apple/kiwi and mango/strawberry share the same value no? @SeanKim to get a list without repetition you can call .distinct() on it.
@RobCo of course, it isn't, but that little incorrectness wasn't really critical here...
it's not ID, it is just quantity of the fruits. :)
Wow! one more! Can I put "All"? and Can it be listed in numerical order? like 1ea, 2ea, 3ea?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.