如何通过使用scala删除重复值将列表列表转换为简单列表?

时间:2014-10-20 06:00:22

标签: list scala collections

我有以下列表 -

List(List(
List(((groupName,group1),(tagMember,["192.168.20.30","192.168.20.20","192.168.20.21"]))), 
List(((groupName,group1),(tagMember,["192.168.20.30"]))),
List(((groupName,group1),(tagMember,["192.168.20.30","192.168.20.20"])))))

我想将其转换为 -

List((groupName, group1),(tagMember,["192.168.20.30","192.168.20.20","192.168.20.21"]))

我尝试使用.flatten但无法形成所需的输出。

如何使用scala获得上述输出?

1 个答案:

答案 0 :(得分:1)

我必须对您的输入进行一些更改才能使其有效。

输入清单:

   val ll = List(List(
      List((("groupName","group1"),("tagMember", List("192.168.20.30","192.168.20.20","192.168.20.21")))),
      List((("groupName","group1"),("tagMember",List("192.168.20.30")))),
      List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20"))))
    ))    
如果组和tagMember在列表中的所有元素

中相同,则

以下代码有效

  def getUniqueIpsConstantGroupTagMember(inputList:  List[List[List[((String, String), (String, List[String]))]]]) = {
      // List[((String, String), (String, List[String]))]
      val flattenedList  = ll.flatten.flatten

      if (flattenedList.size > 0) {
         val group = flattenedList(0)._1
         val tagMember = flattenedList(0)._2._1
         val ips = flattenedList flatMap (_._2._2)

         ((group), (tagMember, ips.distinct))
      } 
         else List()
  }

  println(getUniqueIpsConstantGroupTagMember(ll))

输出:

((groupName,group1),(tagMember,List(192.168.20.30, 192.168.20.20, 192.168.20.21)))

现在,让我们假设您可以拥有不同的groupNames。

示例输入:

  val listWithVariableGroups = List(List(
      List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20","192.168.20.21")))),
      List((("groupName","group1"),("tagMember",List("192.168.20.30")))),
      List((("groupName","group1"),("tagMember",List("192.168.20.30","192.168.20.20")))),
      List((("groupName","group2"),("tagMember",List("192.168.20.30","192.168.20.10"))))   
    ))

以下代码应该有效。

  def getUniqueIpsForMultipleGroups(inputList:  List[List[List[((String, String), (String, List[String]))]]]) = {
    val flattenedList = inputList.flatten.flatten

    // Map[(String, String),List[(String, List[String])]]
    val groupedByGroupNameId = flattenedList.groupBy(p => p._1) map {
      case (key, value) => (key, ("tagMember", extractUniqueTagIps(value)))
    }
    groupedByGroupNameId
  }

  def extractUniqueTagIps(list: List[((String, String), (String, List[String]))]) = {
    val ips = list flatMap (_._2._2)
    ips.distinct
  }

  getUniqueIpsForMultipleGroups(listWithVariableGroups).foreach(println)

输出:

((groupName,group1),(tagMember,List(192.168.20.30, 192.168.20.20, 192.168.20.21)))
((groupName,group2),(tagMember,List(192.168.20.30, 192.168.20.10)))