Saf Saf - 1 year ago 128
Scala Question

Scala - convert a list to a HashMap based on list member variable values

I have an object, A that contains another object, B. B contains two strings, stringOne and stringTwo.

Given that I have a list / sequence of A's,

Is it possible to create a map from the list of A's, that results in a HashMap of type A -> Seq[B], where what goes into Seq[B] are B items with identical B.stringOne and B.stringTwo?

A and B are case classes.

Answer Source

Are you looking for something like this:

case class B(s1: String, s2: String) 
case class A(b: B) 
val ls = List( A(B("1","2")), A(B("3","4")), A(B("5","6")),  A(B("1","2")))
ls.groupBy(identity).map({case (k,v) => (k,})

//Output: Map(A(B(1,2)) -> List(B(1,2), B(1,2)), A(B(3,4)) -> List(B(3,4)), A(B(5,6)) -> List(B(5,6)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download