首页 > 解决方案 > 将每个项目与列表的其余项目进行比较

问题描述

我正在尝试将每个表格列与其他表格的列一一进行比较。

这里是风景

我有三张这样的桌子

我将他们的信息作为 TableRow 列表获取

TableRow(students,INT,10,id)
TableRow(students,VARCHAR,200,name)
TableRow(students,VARCHAR,100,address)

TableRow(department,INT,10,id)
TableRow(department,VARCHAR,100,department_name)

TableRow(teacher,INT,10,id)
TableRow(teacher,INT,10,suvject)

假设我想像这样将每一行与其他表的剩余行进行比较->

TableRow(students,INT,10,id) - TableRow(department,INT,10,id)
TableRow(students,INT,10,id) - TableRow(department,VARCHAR,100,department_name)
TableRow(students,INT,10,id) - TableRow(teacher,INT,10,id)
TableRow(students,INT,10,id) - TableRow(teacher,INT,10,suvject)

TableRow(students,VARCHAR,200,name) - TableRow(department,INT,10,id)
TableRow(students,VARCHAR,200,name) - TableRow(department,VARCHAR,100,department_name)
TableRow(students,VARCHAR,200,name) - TableRow(teacher,INT,10,id)
TableRow(students,VARCHAR,200,name) - TableRow(teacher,INT,10,suvject)

TableRow(students,VARCHAR,100,address) - TableRow(department,INT,10,id)
TableRow(students,VARCHAR,100,address) - TableRow(department,VARCHAR,100,department_name)
TableRow(students,VARCHAR,100,address) - TableRow(teacher,INT,10,id)
TableRow(students,VARCHAR,100,address) - TableRow(teacher,INT,10,suvject)

TableRow(department,INT,10,id) - TableRow(teacher,INT,10,id)
TableRow(department,INT,10,id) - TableRow(teacher,INT,10,subject)

TableRow(department,VARCHAR,100,department_name) - TableRow(teacher,INT,10,id)
TableRow(department,VARCHAR,100,department_name) - TableRow(teacher,INT,10,subject)

因此,我将每个表格列与上面的其他表格列进行比较..

我正在使用这样的代码来比较它,这很有效,但是有没有更好的方法来做到这一点?一个好的函数式编写方式吗?

 val stack = mutable.Stack[TableRow]().pushAll(tableRows)
    val arrayList = new util.ArrayList[JoinInfo]()

    while (stack.nonEmpty) {
      val currentRow = stack.pop()
      stack.foreach(targetRow => {
        if (!(targetRow.tableName.equals(currentRow.tableName) && targetRow.schema.equals(currentRow.schema))) { //not comparing with current table's column with its other column.
          arrayList.add(compareColumns(currentRow, targetRow))
        }
      })
    }

标签: listscalafunctional-programmingiteration

解决方案


我会写这样的东西:

(tableRows zip tableRows).filter {
  case(currentRow, targetRow) => !(targetRow.tableName.equals(currentRow.tableName) && targetRow.schema.equals(currentRow.schema))
}

所以,除了它使用 zip 函数来避免手动编写双循环之外,几乎是一样的。


推荐阅读