I need this function to return a String so I can call it in another function but instead I got any. How can I make it return a String?
private fun getValue(text: String){
myMap.forEach { (k, v) -> v.find {it.key == text}?.values?.joinToString(separator = "#") ?: ""}}
myMap is a Map<UUIDint, List<SomeAttribute>>
SomeAttribute is a data class
data class SomeAttribute(
var key: String = "",
var values: List<String> = ArrayList()
)
I want the output String to look like this 122PR
or 122PR#374DH
respectively.
CodePudding user response:
forEach
method returns Unit
. You need to do some side-effect inside it (modify some variable defined beforehand) and return this variable. But it's better to use other methods, which will immediately return what you need.
Depending on what exactly String
you want to get from this Map
there are several options:
- If you want to get
values
of first metSomeAttribute
which has requiredtext
as akey
, then you need to:
myMap.values.flatten().find { it.key == text }?.values?.joinToString(separator = "#")
- If you want to get
values
of all first metSomeAttribute
s in eachList<SomeAttribute>
, which have requiredtext
as akey
, then you need to:
myMap.values.flatMap { v -> v.find { it.key == text }?.values ?: emptyList() }.joinToString(separator = "#")
- If you want to get
values
of allSomeAttribute
s which has requiredtext
as akey
in eachList<SomeAttribute>
, then you need to:
myMap.values.flatMap { v -> v.filter { it.key == text } }.map { it.values }.joinToString(separator = "#")
CodePudding user response:
if you want it to return the first match it has you could do like this:
private fun getValue(text: String) : String {
myMap.forEach { (_, v) -> v.find {it.key == text}?.values?.joinToString(separator = "#")?.let { return it }}
return ""
}