简体   繁体   中英

How to transform a Set into an Array with commas after each element without allocating new memory in kotlin?

The scenario is the following:

fun scenario(names:Set<String>){
log( /here comes the transformed set );
}

It is important to mention that log receives a varargs type of parameter of type object.

What I tried is the following: *names.toTypeArray().

The problem with this is that, besides allocating new space for the new list, it also misses the required commas

What I want to achieve is something like: log("John", ",", "John", etc...) at runtime.

You can try this.

val arr :Array<String> = (names.chunked(1) // Chunking set into 1 element lists
    .flatMap { it.plus(",") } // Adding comma next to each elements and flatten the list
    .toList() as ArrayList) // Type casting to arraylist
    .also { it.removeLast() } //Removing comma after last element
    .toTypedArray() // Converting to array
someFun(*arr) // Passing array as vararg

One thing to remember here if you want to maintain order of insertion, names set should be LinkedHashSet .As order sets like TreeSet, HashSet.. does not maintain the order.

fun someFun(vararg a: String) {
    a.forEach {
        print(it)
    }
}

Note: This is only an idiomatic solution. Even though we dont use extra space here,it internally does creating extra space.

Hope it helps. Link to Kotlin Playground.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM