fork download
  1. import java.sql.Timestamp
  2.  
  3. case class InputRow(unit:Int, eventName: String, eventTime:java.sql.Timestamp, value: Int) {
  4. override def toString: String = s"$eventTime|$unit|$eventName|$value"
  5. }
  6.  
  7. object Main extends App {
  8. val rows = Seq(
  9. InputRow(2, "B", Timestamp.valueOf("2018-06-02 16:05:11"), 1),
  10. InputRow(1, "A", Timestamp.valueOf("2018-06-02 16:05:12"), 2),
  11. InputRow(2, "A", Timestamp.valueOf("2018-06-02 16:05:13"), 2),
  12. InputRow(1, "A", Timestamp.valueOf("2018-06-02 16:05:14"), 3),
  13. InputRow(2, "A", Timestamp.valueOf("2018-06-02 16:05:15"), 3)
  14. )
  15.  
  16. val grouped: Map[(Int, String), InputRow] =
  17. rows
  18. .foldLeft(Map.empty[(Int, String), Seq[InputRow]]) { case (acc, row) =>
  19. val key = (row.unit, row.eventName)
  20. // Get from the accumulator the Seq that already exists or Nil if
  21. // this key has never been seen begore
  22. val value = acc.getOrElse(key, Nil)
  23. // Update the accumulator
  24. acc + (key -> (value :+ row))
  25. }
  26. // Get the last element from the list of rows when grouped by unit and event.
  27. .map({case (k, v) => k -> v.last})
  28.  
  29. grouped.values.foreach { row =>
  30. println(row)
  31. }
  32. }
  33.  
Success #stdin #stdout 0.45s 67456KB
stdin
Standard input is empty
stdout
2018-06-02 16:05:11.0|2|B|1
2018-06-02 16:05:14.0|1|A|3
2018-06-02 16:05:15.0|2|A|3