Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jaytaylor/3504765 to your computer and use it in GitHub Desktop.
Save jaytaylor/3504765 to your computer and use it in GitHub Desktop.
Scala query string parser using Java Collections
import java.net.URLDecoder
import java.util.{ArrayList, HashMap, List, Map}
import scala.collection.JavaConversions._
/**
* Parse the query string portion of a string containing a URI or URL.
*/
/**
* Parse the query string portion of a string containing a URI or URL.
*/
def parseUriParameters(uri: String): Map[String, List[String]] = {
val params = new HashMap[String, List[String]]()
val parts = uri split "\\?"
if (parts.length > 1) {
val query = parts(1)
query split "&" map { param =>
val pair = param split "="
val key = URLDecoder.decode(pair(0), "UTF-8")
val value = pair.length match {
case l if l > 1 => URLDecoder.decode(pair(1), "UTF-8")
case _ => ""
}
val values = Option(params get key) match {
case Some(values) => values
case None =>
val v = new ArrayList[String]()
params.put(key, v)
v
}
values add value // NB: The value may be an empty string.
}
}
params
}
@JMathnov
Copy link

JMathnov commented May 13, 2020

Refactored this to be pure Scala

def parseUriParameters(uri: String): Map[String, Seq[String]] = {
    val parts = uri split "\\?"
    if (parts.length > 1) {
      val query = parts(1)
      val utf8 = "UTF-8"
      query.split("&").flatMap{queryString =>
        val fullQueryParam = queryString.split("=")
        val keyValues = fullQueryParam.headOption.flatMap(key => fullQueryParam.drop(1).headOption.map(value => URLDecoder.decode(key, utf8) -> URLDecoder.decode(value, utf8)))
        keyValues
      }.groupBy(_._1).mapValues(_.toVector.map(_._2))
    } else Map.empty
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment