我想将一组整数转换为varargs(字符串数组),反之亦然。
在Kotlin中,有没有比下面的代码更有效的方法?
// SET<INT> -> VARARGS
// intIds: Set<Int>
val stringIds = intIds.toTypedArray().map { i -> i.toString() }.toTypedArray()
//to get varargs, use *stringIds
// SET<STRING> -> SET<INT>
// val stringIds: Set<String>
val intIds = stringIds?.stream()?.map { i -> i.toInt() }?.collect(Collectors.toSet())
答案 0 :(得分:2)
这有点简单
val stringIds = intIds.map { it.toString() }.toTypedArray()
//to get varargs, use *stringIds
// SET<STRING> -> SET<INT>
// val stringIds: Set<String>
val intIds2 = stringIds.map { it.toInt() }.toSet()
答案 1 :(得分:1)
val stringIds = arrayOfNulls<String>(intIds.size)
intIds.forEachIndexed { idx, it -> stringIds[idx] = it.toString() }
stringIds as Array<String> // assert no null elements here
// ^^ or you can create your own `mapToArray` extension
val intIds = stringIds.mapTo(HashSet(), String::toInt)