Java – replacing stream collection in kotlin native solutions

I am currently using the kotlin function to extract a map from a JSON structure with key value pairs

The JSON used to build the map contains tags and values:

"values": [
{
  "label": "Email","value": "email"
},{
  "label": "Social media","value": "socialMedia"
},{
  "label": "Word of mouth","value": "wordOfMouth"
},{
  "label": "Newspaper","value": "newspaper"
}
],

JSON "tag" should become the key of the map, and "value" should become its value

This is the code that uses the stream collection method of Java 8 to extract and convert JSON into mapping

fun extractValue(jsonNode: JsonNode?): Map<String,String> {
    val valuesNode = jsonNode?.get("values") ?: mapper.createArrayNode()
    return valuesNode.map { Pair(it.get("label")?.asText() ?: "",it.get("value")?.asText() ?: "") }
            .stream().collect({ HashMap<String,String>()},{ m,p -> m.put(p.first,p.second) },p -> })
}

How do you write parts in stream() Collect the customary kotlin? What alternatives do you have

In this special case?

Solution

So you have a list of pairs that you want to convert into a map? You can replace your with kotlin's tomap() stream(). collect(…).

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-map.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>