How to build a tree hierarchy from a list in groovy using recursive closure?

I defined a recursive domain class in grails:

class Work {

  String code
  String title
  String description
  static hasMany = [subWorks:Work]
  static mappedBy = [subWorks: 'parentWork']

  Work getRootWork(){
    if(parentWork) return parentWork.getRootWork()
      else return this
  }

  boolean isLeafWork(){
    return subWorks.isEmpty()
  }

  boolean isRootWork(){
    return !parentWork
  }

I have a Works list, but the hierarchy structure has not yet been built. The structure looks like this:

def works = [new Work(code:'A', title:'TitleA'), 
    new Work(code:'B', title:'TitleB'), 
    new Work(code:'A.1', title:'Titile A.1'), 
    new Work(code:'B.1', title:'Title B.1'),
    new Work(code:'B.2', title:'Title B.2'),
    new Work(code:'B.3', title:'Title B.3'), 
    new Work(code:'B.2.2', title:'Title B.2.2'),
    new Work(code:'B.2.3', title:'Title B.2.3'),
    new Work(code:'A.1.1', title:'Title A.1.1'),
    new Work(code:'A.1.2', title:'Title A.1.2'),]

I need to create a hierarchical relationship between these works based on the intended code. for example A.1 - the first children's work A; B.1.1 is the first child of B.1 whose parent is B. I know that Groovy supports recursive closures to build such a hierarchical structure. How to achieve your goal using Groovy recursive closure, for example, sample number JN2515 Fibonacci, in Groovy's official documentation? Many thanks!

+5
source share
2 answers

like this...?

def root = new Work(code:'*', title:'ROOT')

def build 

build = { p, list ->
  list.groupBy{it.code.split('\\.').first()}.each{ el, sublist ->
    el = sublist[0]        
    el.parentWork = p
    if(sublist.size()>1){
        build(el, sublist[1..-1] )
    }
  }

}
build(root, works.sort{it.code.length()})

,

def root = new Work(code:'*', title:'ROOT')

{ p, list ->
  list.groupBy{it.code.split('\\.').first()}.each{ el, sublist ->
    el = sublist[0]        
    el.parentWork = p
    if(sublist.size()>1){
      call(el, sublist[1..-1] )
    }
  }

}(root, works.sort{it.code.length()})
+3

Grails, , , , , : work1.parentWork = work2, work1 in work2.subWorks . , , , parentWork , : X.Y.Z X.Y, X :

def works = [new Work(code:'A', title:'TitleA'),
    new Work(code:'B', title:'TitleB'),
    new Work(code:'A.1', title:'Titile A.1'),
    new Work(code:'B.1', title:'Title B.1'),
    new Work(code:'A.1.1', title:'Title A.1.1')]

def worksByCode = works.collectEntries { [it.code, it] }

works.each {
    if (it.code.contains('.')) {
        def parentCode = it.code[0..it.code.lastIndexOf('.') - 1]
        it.parentWork = worksByCode[parentCode]
    }
}
+1

All Articles