How to sort a list by existing properties

前端 未结 3 1533
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 00:46

I am using this line here to sort a list based on the object\'s name.

g.V.sort{it.name}

How do I sort it based on \"name\" if it exists, if not

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-15 01:02

    This is my totally untested effort which is probably riddled with bugs

    def comparator = {o1, o2 ->
    
      // wording of question suggests title will always exist, if not, add more hasProperty checks  
      def diff = o1.title <=> o2.title
    
      if (o1.hasProperty('name') && o2.hasProperty('name')) {  
        def nameDiff = o1.name <=> o2.name
    
        if (nameDiff != 0) {
          diff = nameDiff
        }
      } 
      diff
    
    } as Comparator
    
    
    def someList = []
    // populate the list...    
    someList.sort(comparator)
    

提交回复
热议问题