我如何重新排序列表说:
['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))