scala - How do I access "filtered" items from collection? -


i have string val trackingheader = "k1=v1, k2=v2, k3=v3, k4=v4" parse , convert map(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4). following code used this:

val trackingheadersmap = trackingheader   .replaceall("\\s", "")   .split(",")   .map(_ split "=")   .map { case array(k, v) => (k, v) }   .tomap 

i able desired output. but, need handle malformed input case val trackingheader = "k1=v1, k2=v2, k3=v3, k4=". notice there no value key k4. above code start breaking scala.matcherror: [ljava.lang.string;@622a1e0c (of class [ljava.lang.string;) changed to:

val trackingheadersmap = trackingheader   .replaceall("\\s", "")   .split(",")   .map(_ split "=")   .collect { case array(k, v) => (k, v) }   .tomap 

great have handle malformed case using collect know key had issue , log (in example k4). tried following , able desired result not sure if right way it:

val badkeys = trackingheader     .replaceall("\\s", "")     .split(",")     .map(_ split "=")     .filternot(_.length == 2) 

now can iterate on badkeys , print them out. there better way this?

you make result optional, , use flatmap instead of map

 .flatmap {     case array(k, v) => some(k -> v)     case array(k) => println(s"bad entry: $k"); none   } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -