Chris
Chris

Reputation: 807

Scala - Mapping into a nested list and sorting on each level of list

I have a function that returns a list of objects containing a list of child objects, where each child object can have children, and so on until an unknown level.

I want to be able to sort each level of the list until there's no more items to sort. I currently have a map that does this but only for the top level list items.

def nestedList(params): Future[List[CustomObject]] = {
    getNestedList(params).map {
    items =>
        items.sortBy(i => i.name)
    }
}

This returns a Future[List[CustomObject]] where custom object is CustomObject(name, List[CustomObject]))

How can I change this to return the entire list sorted?

Upvotes: 1

Views: 598

Answers (2)

Vüsal
Vüsal

Reputation: 2706

Let's suppose your CustomObject class looks like:

class CustomObject(val name: String, val children: List[CustomObject])

and you said there are unknown levels of children.
Then you can use the next function to sort your List of CustomObjects recursively:

def sortCustomObjects(a: List[CustomObject]): List[CustomObject] = {
  a.sortBy(_.name).map(co => new CustomObject(co.name, sortCustomObjects(co.children)))
}

Please, note - I use recursion and it's not tail recursion - so you can get StackOverflow in large inputs.


UPD 1:
You can also define CustomeObject as a case class and use .copy method in a more functional way:

case class CustomObject(name: String, children: List[CustomObject])

def sortCustomObjects(a: List[CustomObject]): List[CustomObject] = {
  a.sortBy(_.name).map(co => co.copy(children = sortCustomObjects(co.children)))
}

Upvotes: 3

Mario Galic
Mario Galic

Reputation: 48420

Say we have

val listsF = Future(List(List(1,3,54,6,3), List(9,7,8,4,3,3)))

then

listsF.map(_.map(_.sorted))

should do the job.

Upvotes: 2

Related Questions