chibis
chibis

Reputation: 858

List to List of Lists in Scala

I am learning Scala and this idea of immutability is still confusing so if the question sounds obvious, just point me in the right direction please

if I have a List of objects with id, groupId and name

List(
Obj(1, 1, "1.1")
Obj(2, 1, "1.2")
Obj(3, 1, "1.3")
Obj(1, 2, "2.1")
Obj(2, 2, "2.2")
Obj(1, 3, "3.1")

what is the right way to create something like this off of it in Scala. (The items are not necessarily ordered by groupId)

List(
    List(
        Obj(1, 1, "1.1")
        Obj(2, 1, "1.2")
        Obj(3, 1, "1.3")
    ), List(
        Obj(1, 2, "2.1")
        Obj(2, 2, "2.2")
    ), List(
        Obj(1, 3, "3.1")
    )
)

Should I use for or map or there some other approaches?

Upvotes: 0

Views: 186

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

Scala immutable collections provide higher order functions such as map, foldLeft, groupBy, etc., which produce a new transformed collection without mutating the old collection. For example, consider groupBy followed by values

objs             // List[Obj]
  .groupBy(_.y)  // Map[Int,List[Obj]]
  .values        // Iterable[List[Obj]]

given

case class Obj(x: Int, y: Int, s: String)

val objs =
  List(
    Obj(1, 1, "1.1"),
    Obj(2, 1, "1.2"),
    Obj(3, 1, "1.3"),
    Obj(1, 2, "2.1"),
    Obj(2, 2, "2.2"),
    Obj(1, 3, "3.1"),
  )

which outputs

Iterable(
  List(Obj(1,1,1.1), Obj(2,1,1.2), Obj(3,1,1.3)), 
  List(Obj(1,2,2.1), Obj(2,2,2.2)), 
  List(Obj(1,3,3.1))
)

Consider working through List interactive exercises and asking on Scala gitter channel for real-time beginner friendly guidance.

Upvotes: 2

Related Questions