0

I am trying to get JSON data into a spinner.

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

this is the output:

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

I want to get only one set of the sizes into a spinner not 5 of them. I have also tried:

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

The output was:

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]

Please help. Thank you!

3
  • What was the idea behind toSet().toList().toString()? Commented Nov 17, 2020 at 3:45
  • 1
    check this stackoverflow.com/questions/40430297/… Commented Nov 17, 2020 at 3:48
  • I was looking for a solution and the toSet().toList().toString() came up Commented Nov 17, 2020 at 12:11

1 Answer 1

2

You should convert the list to a Set before you join, not after

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

The output then will be

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

You can also use distincBy to omit a map operator.

val product_sizes = productfeed.variants
                               .distincBy { it.option_values[0].name }
                               .joinToString { it.option_values[0].name }
Log.d("TAG", "TESTING:: ${product_sizes} ")
Sign up to request clarification or add additional context in comments.

Comments

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.