Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an element to the first position of a List in groovy

Tags:

list

groovy

how do I reorder the list say:

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

if user select banana, the list becomes

['banana', 'apple', 'orange']
like image 439
user903772 Avatar asked Dec 24 '12 06:12

user903772


3 Answers

Another way to do it:

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)
like image 184
Jay Prall Avatar answered Nov 15 '22 10:11

Jay Prall


Split into two lists and recombine - easily generalized for non-String lists:

List<String> moveToStart(List<String> original, String input) {
  original.split {it.equals(input)}.flatten()
}
like image 28
James Neale Avatar answered Nov 15 '22 10:11

James Neale


List pickToFirst(List list, int n) {
    return list[n,0..n-1,n+1..list.size()-1]
}

In your case,

    def list = ['apple', 'banana', 'orange']
    def newList = pickToFirst(list, 1)
like image 20
coderLMN Avatar answered Nov 15 '22 08:11

coderLMN