以一种不寻常的方式在Groovy中对列表进行排序 [英] Sorting a list in Groovy in an unusual way

查看:117
本文介绍了以一种不寻常的方式在Groovy中对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,例如 [Cat,Dog,Cow,Horse] ,我想按以下方式排序




  • 如果 Cat 位于列表中,它应该排在第一位

  • 如果 Cow 在列表中,它应该排在第二位

  • 其余元素应按字母顺序排列。



有什么建议可以在Groovy中做到这一点?

解决方案
  def highPriority = ['Cat','Cow'] 

def list = ['Armadillo ','狗','牛','斑马','马','牛','猫']

def remaining =(list - highPriority).sort()

list.retainAll(highPriority)

list.sort {highPriority.indexOf(it)} +余数

这会给你牛两次。如果你不想重复,使用相交很简单。

  def highPriority = ['Cat','Cow'] 

def list = ['Armadillo ','Dog','Cow','Zebra','Horse','Cow','Cat']

list.intersect(highPriority).sort {highPriority.indexOf(it)} +(list - highPriority).sort()


I have a list of, let's say [Cat, Dog, Cow, Horse], that I want to be sorted in the following way

  • if Cat is on the list it should come first
  • if Cow is on the list it should come second
  • The rest of the elements should come after in alphabetic order.

Any suggestions how this could be done in Groovy?

解决方案

Tim's answer is pretty clever. I'm personally more a fan of just using list operations as the code it generates is slightly easier to read.

def highPriority = [ 'Cat', 'Cow' ]

def list = [ 'Armadillo', 'Dog', 'Cow', 'Zebra', 'Horse', 'Cow', 'Cat' ]

def remainder = ( list - highPriority ).sort()

list.retainAll( highPriority )

list.sort{ highPriority.indexOf( it ) } + remainder

That will give you Cow twice. If you don't want duplicates, using intersect is fairly simple.

def highPriority = [ 'Cat', 'Cow' ]

def list = [ 'Armadillo', 'Dog', 'Cow', 'Zebra', 'Horse', 'Cow', 'Cat' ]

list.intersect( highPriority ).sort{ highPriority.indexOf( it ) } + ( list - highPriority ).sort()

这篇关于以一种不寻常的方式在Groovy中对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆