我有一個場景,我根據條件在scala中壓縮兩個列表。 它們可能不是按順序排列的。什麼是最好的方式來做到這一點?基於條件的壓縮非順序列表
我想將具有相同requestId的DirectRetailCM和DirectRetailCM分組爲一個元組。
object Main extends App {
case class SalesDoc(val id: Int, val name: String, val requestId: String) {}
val list = List(
SalesDoc(1, "ILLEGAL", "1"),
SalesDoc(2, "DirectRetailCM", "1"),
SalesDoc(3, "DirectRetailOffsetInvoice", "2"),
SalesDoc(4, "DirectRetailCM", "2"),
SalesDoc(5, "OTHER", "2"),
SalesDoc(5, "DirectRetailCM", "LEFTOUT"),
SalesDoc(6, "ILLEGAL2", "4"),
SalesDoc(5, "OTHER", "3"),
SalesDoc(7, "DirectRetailOffsetInvoice", "4"),
SalesDoc(8, "DirectRetailCM", "4")
)
// I expect zip results of drOffsetInvoice and drCms as
List(
(SalesDoc(3, "DirectRetailOffsetInvoice", "2"), SalesDoc(4, "DirectRetailCM", "2")),
(SalesDoc(7, "DirectRetailOffsetInvoice", "4"), SalesDoc(8, "DirectRetailCM", "4"))
)
}
,我能想到的初始方法是
- 組directRetailCM - list.filter(E => e.name == 「DirectRetailCM」)
- 組DirectRetailOffsetInvoice - list.filter (E => e.name == 「DirectRetailOffsetInvoice」)
- 郵編兩個 - 但可能不會按順序
- 有可能是沒有對應物的行
您能否建議我需要考慮的其他方法?
感謝泰勒,我可能會使用一個更多的DirectRetailCM過濾器來避免每個DirectRetailOffsetInvoice循環。 –
如果您的行比您的示例建議的多得多,那麼您可能需要構建地圖,以便查找速度更快。 – Tyler