Skip to content

Instantly share code, notes, and snippets.

@skuppa
Last active February 13, 2018 15:32
Show Gist options
  • Save skuppa/1fa7ccb172e5d18376d7 to your computer and use it in GitHub Desktop.
Save skuppa/1fa7ccb172e5d18376d7 to your computer and use it in GitHub Desktop.
Scala Collection

Merge collection by group by

case class Channel(name: String,
                  deviceIds: List[String])

object Channel {
  def copy(c: Channel, newDevicesIds: List[String]) = c.copy(deviceIds = if(c.deviceIds == newDevicesIds) c.deviceIds else c.deviceIds ::: newDevicesIds)
}

def mergeDevices(channels: List[Channel]): Channel = { channels.foldLeft(channels.head) ((r, c) => Channel.copy(r, c.deviceIds)) }

val ch1d1 = Channel("Ch1", List("D1"))
val ch1d2 = Channel("Ch1", List("D2"))
val ch1d3 = Channel("Ch1", List("D3"))
val ch2d1 = Channel("Ch2", List("D1"))
val devices = List(ch1d1, ch1d2, ch2d1, ch1d3)

val deviceByNames = devices.groupBy(_.name)
val groupsByChannelName = deviceByNames.values.map(mergeDevices)

println (s"deviceByNames $deviceByNames")
println (s"groupsByChannelName $groupsByChannelName")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment