How to convert from from java.util.Map to a Scala Map

后端 未结 4 1653
挽巷
挽巷 2021-02-07 12:58

A Java API returns a java.util.Map;. I would like to put that into a Map[String,Boolean]

So imagine w

4条回答
  •  梦如初夏
    2021-02-07 13:33

    At least with Scala 2.9.2 there's an easier way with the collections conversions: import "import collection.JavaConversions._" and use "toMap".

    Example:

    // show with Java Map:
    
    scala> import java.util.{Map=>JMap}
    scala> val jenv: JMap[String,String] = System.getenv()
    jenv: java.util.Map[String,String] = {TERM=xterm, ANT_OPTS=-Xmx512m ...}
    
    scala> jenv.keySet()
    res1: java.util.Set[String] = [TERM, ANT_OPTS...]
    
    // Now with Scala Map:
    
    scala> import collection.JavaConversions._
    scala> val env: Map[String,String] = System.getenv.toMap // <--- TADA <---
    env: Map[String,String] = Map(ANT_OPTS -> -Xmx512m, TERM -> xterm ...)
    
    // Just to prove it's got Scala functionality:
    
    scala> env.filterKeys(_.indexOf("TERM")>=0)
    res6: scala.collection.immutable.Map[String,String] = Map(TERM -> xterm, 
      TERM_PROGRAM -> iTerm.app, ITERM_PROFILE -> Default)
    

    It works fine with a java.util.map of String to Boolean.

提交回复
热议问题