Reputation: 4685
I have a collection of
case class User(id: Int, parentId: Int)
val users = Seq(User(3, 23), User(4, 17), User(22, 23),User(29, 90))
I need do efficient (less than O(n)) search by "parentId":
val testUser = User(23, 999)
val found = users.filter(u => u.parentId == testUser.id)
res: List(User(3,23), User(22,23))
How I can achive this and which data structure to use?
Upvotes: 1
Views: 117
Reputation: 1544
Use groupBy to convert your Seq to a Map, which will give you O(1) lookup:
case class User(id: Int, parentId: Int)
val users = Seq(User(3, 23), User(4, 17), User(22, 23),User(29, 90))
val usersMap = users.groupBy(_.parentId)
val testUser = User(23, 999)
val found = usersMap.get(testUser.id)
Upvotes: 3