9

List("a,1" , "b,2" , "c,3" , "a,2" , "b,4")値を持つ型に変換しようとしscala.collection.immutable.HashMap[String, java.util.List[String]]ています:

a -> 1,2
b -> 2,4
c -> 3

したがって、各キーにはその値のリストが含まれています。

これまでの私のコードは次のとおりです。

object ConvertList extends Application {

  var details = new scala.collection.immutable.HashMap[String, java.util.List[String]]

  val strList = List("a,1" , "b,2" , "c,3" , "a,2" , "b,4")

  //Get all values
  val getValue : Function1[String, String] = { a => a.split(",")(1) }
  val allValues : List[String] = strList map getValue

  //get unique values
  val uniqueValues = allValues.toSet[String]

  //Somehow map each unique value to a value in the original List....
  println(uniqueValues)

  println(strList.flatten)
  //userDetails += "1" -> List("a","b",


}

この変換はどのように実行できますか?

4

5 に答える 5

14
strList.map(s => (s(0).toString,s(2).toString))
       .groupBy(_._1)
       .mapValues(_.map(_._2))

出力:

Map[String,List[String]] = Map(b -> List(2, 4), a -> List(1, 2), c -> List(3))
于 2013-08-29T20:58:55.740 に答える
3

リストは同じ順序ではありませんが、一般的には非常に実行可能な問題です:

// for a sake of pithiness
type M = Map[String,List[String]] 
def empty: M = Map.empty.withDefaultValue(Nil)

@annotation.tailrec
def group(xs: List[String], m: M = empty): M = xs match {
    case Nil     => m
    case h::tail => 
      val Array(k,v) = h.split(",")
      val updated = v::m(k)
      combine(tail, m + (k -> updated))
}
于 2013-08-29T20:58:08.953 に答える
1
scala> List("a,1" , "b,2" , "c,3" , "a,2" , "b,4")
res0: List[String] = List(a,1, b,2, c,3, a,2, b,4)

scala> res0.groupBy(xs => xs.split(",")(0)).mapValues(xs => xs.flatMap(xs => xs.toCharArray.filter(_.isDigit)))
res2: scala.collection.immutable.Map[String,List[Char]] = Map(b -> List(2, 4), a -> List(1, 2), c -> List(3))

を使用groupByすると、これが簡単になりますMap。はbyのgroupBy各要素を分割し、キーである最初の要素を取ります。これにより、次のようになります 。ここからは、各値から桁を取得する処理です。List,scala.collection.immutable.Map[String,List[String]] = Map(b -> List(b,2, b,4), a -> List(a,1, a,2), c -> List(c,3))List

これは を返しますMap[String, List[Char]]scala.collection.immutable.HashMap[String, java.util.List[String]]返品したい場合は、もう少しやるべきことがありますが、それは簡単な部分です.

于 2013-08-29T20:58:16.447 に答える