2

I hope to get a name array from a list of MSetting, at present, I use Code A to do it, but it's too complex, is there a simple way to do it?

Code A

  fun getName(aList:List<MSetting>): Array<CharSequence>{
        if (aList.isEmpty()){
            return emptyArray<CharSequence>()
        }else{
            var aa=Array<CharSequence>(aList.size,{""})
            for (index in aList.indices){
                aa[index]=aList[index].name
            }
            return aa
        }
    }

Data

data class MSetting (
        var _id: Long,  
        var name: String,
        var createdDate: Long,
        var description: String
)

3 Answers 3

13

The solution here is using map and then toTypedArray:

fun getName(aList: List<MSetting>): Array<CharSequence> {
    return aList.map { it.name }.toTypedArray()
}
Sign up to request clarification or add additional context in comments.

Comments

7

using map operator

var names = msettings.map { it -> it.name}

names is a list content all value of name from msettings

hope this helps

2 Comments

Hey @gianhtran is there any other method instead of map?
well kotlin have a lot of method using for collection, depend on your purpose . you can see here kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/…
2

map work for me

val names = list.map { it.name }

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.