如何在groovy中将元素移动到List的第一个位置



如何重新排序列表,比如:

['apple', 'banana', 'orange']

如果用户选择香蕉,列表将变为

['banana', 'apple', 'orange']

另一种方法:

def list = ['apple', 'banana', 'orange']
// get a reference to the selection (banana)
def pick = list.find { it == 'banana' }
// remove selection from the the list
def newList = list.minus(pick)
// add selection back at the beginning
newList.add(0, pick)

拆分为两个列表并重新组合-对于非字符串列表很容易概括:

List<String> moveToStart(List<String> original, String input) {
  original.split {it.equals(input)}.flatten()
}
List pickToFirst(List list, int n) {
    return list[n,0..n-1,n+1..list.size()-1]
}

在您的情况下,

    def list = ['apple', 'banana', 'orange']
    def newList = pickToFirst(list, 1)

从未来的2022年开始回答,因为我必须查找它;使用+和-。

arr = ["lol", "rofl", "omg"]
selected = "omg"
println([selected] + (arr - selected))

最新更新