Scala - 将List / Map重新格式化/分组到地图的更好方法

时间:2017-04-04 06:15:10

标签: scala

我遇到了以最佳方式或正确方式对功能方式的分组/格式化进行编码的问题。

样本列表是这个

 val list = List (
        Map(
          "name" -> "AAA",
          "id" -> "1",
          "category" -> "1",
          "sub_category" -> "1"
        ),

        Map(
          "name" -> "BBB",
          "id" -> "2",
          "category" -> "1",
          "sub_category" -> "2"
        ),

        Map(
          "name" -> "CCC",
          "id" -> "3",
          "category" -> "1",
          "sub_category" -> "2"
        ),

        Map(
          "name" -> "DDD",
          "id" -> "4",
          "category" -> "2",
          "sub_category" -> "1"
        ),

        Map(
          "name" -> "EEE",
          "id" -> "5",
          "category" -> "2",
          "sub_category" -> "2"
        )
      )

我想按类别和sub_category分组。预期的结果是这个

Map(
        2 -> Map(
          2 -> MutableList(
            Map(name -> EEE, id -> 5, category -> 2, sub_category -> 2)
          ),

          1 -> MutableList(
            Map(name -> DDD, id -> 4, category -> 2, sub_category -> 1)
          )
        ),

        1 -> Map(
          2 -> MutableList(
            Map(name -> BBB, id -> 2, category -> 1, sub_category -> 2),
            Map(name -> CCC, id -> 3, category -> 1, sub_category -> 2)
          ),

          1 -> MutableList(
            Map(name -> AAA, id -> 1, category -> 1, sub_category -> 1)
          )
        )
      )

预期的输出可以包含List或MutableList,我已经完成了像这样的代码

val filtered:mutable.Map[Int,mutable.Map[Int,mutable.MutableList[Map[String,String]]]] =  mutable.Map()

      for(each <- list) {

        if(filtered.contains(each("category").toInt)) {

          if(filtered(each("category").toInt).contains(each("sub_category").toInt)) {

            filtered(each("category").toInt)(each("sub_category").toInt) += each

          } else {
            filtered(each("category").toInt) += (
              each("sub_category").toInt -> mutable.MutableList(each)
              )
          }
        } else {
          filtered += (
            each("category").toInt -> mutable.Map(each("sub_category").toInt -> mutable.MutableList(each))
            )
        }
      }

我得到了结果,这不是我希望以正确的方式做到这一点的功能性方式任何人都可以帮助我......?

1 个答案:

答案 0 :(得分:2)

我认为这会得到您正在寻找的结果。

list.groupBy(_("category")).mapValues(_.groupBy(_("sub_category")))

我不得不说,看起来您正在使用Map,其中设计精良的case class将是更好的方式。