如何按其他列表的排序顺序对scala对象列表进行排序?

时间:2017-07-11 09:22:46

标签: scala

我在scala中有以下两个列表。

group by week(STR_TO_DATE(a.datecreated,'%d/%m/%y'))

现在我的parenList被排序按降序排序,我希望我的childrenList按照它跟随parentList Order的方式排序。 即预期订单将遵循

    case class Parents(name: String, savings: Double)
    case class Children(parentName: String, debt: Double)

    val parentList:List[Parents] = List(Parents("Halls",1007D), Parents("Atticus",8000D), Parents("Aurilius",900D))

    val childrenList:List[Children] = List(Children("Halls",9379.40D), Children("Atticus",9.48D), Children("Aurilius",1100.75D))

    val sortedParentList:List[Parents] = parentList.sortBy(_.savings).reverse

// sortedParentList = List(Parents(Atticus,8000.0), Parents(Halls,1007.0), Parents(Aurilius,900.0))

2 个答案:

答案 0 :(得分:6)

好吧,如果您知道两个列表最初的顺序相同(您可以始终通过按名称排序),那么您可以一次性对它们进行排序:

 val (sortedParentList, sortedChildrenList) = (parents zip children)
   .sortBy(-_._1.savings)
   .unzip

或者您可以提前定义排序,并使用它对两个列表进行排序:

val order = parentList.map(p => p.name -> -p.savings).toMap
val sortedParentList = parentList.sortBy(order(_.name))
val sortedChildrenList = childrenList.sortBy(order(_.parentName))

或者您可以先对父母进行排序(可能已经对它们进行了排序),然后定义顺序:

val order = sortedParentList.zipWithIndex.map { case(p, idx) => p.name -> idx }.toMap
val sortedChildrenList = childrenList.sortBy(c => order(c.parentName))

答案 1 :(得分:1)

case class Parents(name: String, savings: Double)
case class Children(parentName: String, debt: Double)

val familiesList: List[(Parents, Children)] = List(
  Parents("Halls",1007D) -> Children("Halls",9379.40D),
  Parents("Atticus",8000D) -> Children("Atticus",9.48D),
  Parents("Aurilius",900D) -> Children("Aurilius",1100.75D))

val (sortedParents, sortedChildren) = familiesList.sortBy {
  case (parents, _) => -parents.savings
}.unzip