[英]How to move an element to the first position of a List in groovy
我如何重新排序列表說:
['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 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)
分成兩個列表並重新組合 - 很容易推廣到非字符串列表:
List<String> moveToStart(List<String> original, String input) {
list.split {it.equals(input)}.flatten()
}
從 2022 年的未來一年開始回答,因為我必須查一下; 使用 + 和 -。
arr = ["lol", "rofl", "omg"]
selected = "omg"
println([selected] + (arr - selected))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.