Scala中如何对两列列表型时间戳逐元素比较并返回列表结果?
Got it, let's break down how to solve this problem where you need to compare two lists of timestamps element-wise and return a corresponding result list. We'll handle edge cases like null values, empty lists, and mismatched list lengths as shown in your example.
Step 1: Set Up Timestamp Parsing
First, we need a way to convert timestamp strings into a comparable date-time type. We'll use Java's LocalDateTime (perfect for handling full timestamps with hours/minutes/seconds) and a formatter matching your input format. We'll also explicitly handle the "null" string.
import java.time.LocalDateTime import java.time.format.DateTimeFormatter import scala.util.Try // Define the formatter matching your timestamp format val timestampFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") // Helper function to parse a timestamp string into an Option[LocalDateTime] def parseTimestamp(tsStr: String): Option[LocalDateTime] = { if (tsStr.trim == "null") None else Try(LocalDateTime.parse(tsStr, timestampFormatter)).toOption }
Step 2: Define Element-Wise Comparison Logic
Next, create a function that takes two timestamp strings, parses them, and returns the appropriate result:
"Less"if the first timestamp is earlier than the second"Great"if the first timestamp is later than the second"Equal"if they match (added for completeness, even though your example doesn't show this case)"Not Okay"if either timestamp isnull, unparseable, or missing
def compareSingleTimestamp(ts1: String, ts2: String): String = { (parseTimestamp(ts1), parseTimestamp(ts2)) match { case (Some(t1), Some(t2)) => if (t1.isBefore(t2)) "Less" else if (t1.isAfter(t2)) "Great" else "Equal" case _ => "Not Okay" } }
Step 3: Handle List-to-List Comparison
To compare entire lists, we'll use zipAll to align elements from both lists. This ensures we handle mismatched lengths by treating missing elements as "null" (which triggers the "Not Okay" result).
def compareTimestampLists(list1: List[String], list2: List[String]): List[String] = { // Zip the lists, filling missing elements with "null" list1.zipAll(list2, "null", "null").map { case (a, b) => compareSingleTimestamp(a, b) } }
Test with Your Example Inputs
Let's verify this works with your sample data:
Test Case 1
val date1 = List("2016-11-24 12:06:47") val date2 = List("2017-10-04 03:30:23") compareTimestampLists(date1, date2) // Output: List("Less")
Test Case 2
val date1 = List("null") val date2 = List.empty[String] compareTimestampLists(date1, date2) // Output: List("Not Okay")
Test Case 3
val date1 = List("2017-01-25 10:07:25", "2018-01-25 10:07:25") val date2 = List("2017-09-15 03:30:16", "2017-09-15 03:30:16") compareTimestampLists(date1, date2) // Output: List("Less", "Great")
Key Notes
- Edge Case Handling: Mismatched list lengths,
nullvalues, and invalid timestamp formats all result in"Not Okay"for the corresponding position. - Robustness: The
parseTimestampfunction usesTryto catch any parsing errors (like invalid date formats), so it's resilient to bad input. - Flexibility: You can remove the
"Equal"case if you don't need it—just adjust the pattern match to omit that branch.
内容的提问来源于stack exchange,提问作者Nith

