Al-Punk
Al-Punk

Reputation: 3660

Groovy convert a flat list of lists to a hierarchy

Assuming we have a flat list of lists in groovy, like the following:

[[id: 1,title: A],[id: 2, title: B],[id: 3, title: C]]

What is the fastest way to transform it in a hierarchy where B is children to A and C is Children to B?

I can do this with iterations, but since groovy is so creative, I am wondering if there is a smarter way.

Upvotes: 1

Views: 376

Answers (1)

tim_yates
tim_yates

Reputation: 171084

You can do this sort of thing if you don't mind mutating your original list and its elements:

def list = [[id: 1,title: 'A'],[id: 2, title: 'B'],[id: 3, title: 'C']]

list.inject( [:] ) { prev, next ->
  if( prev ) {
      prev.child = next
  }
  next
}

assert list.head() == [id:1, title:'A', child:[id:2, title:'B', child:[id:3, title:'C']]]

Upvotes: 3

Related Questions