Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the selected item to move to the top of the list

Tags:

java

List<String> strings; // contains "foo", "bar", "baz", "xyz"

and if given an input "baz" the function re-arrange(String input) should return the strings

"baz", "foo", "bar", "xyz"

and if given an input "bar" the function re-arrange(String input) should return the strings

"bar", "foo", "baz", "xyz"
like image 508
user339108 Avatar asked Mar 16 '11 05:03

user339108


4 Answers

First, remove the item and then add the item again at position 1.

List<String> strings;

List<String> rearrange(String input) {
    strings.remove(input);
    strings.add(0,input);
    return strings;
}
like image 182
sstendal Avatar answered Nov 15 '22 19:11

sstendal


public static <T> List<T> rearrange(List<T> items, T input) {
  int index = items.indexOf(input);
  List<T> copy;
  if (index >= 0) {
    copy = new ArrayList<T>(items.size());
    copy.add(items.get(index));
    copy.addAll(items.subList(0, index));
    copy.addAll(items.subList(index + 1, items.size()));
  } else {
    return items;
  }
  return copy;
}
like image 31
Mike Samuel Avatar answered Nov 15 '22 21:11

Mike Samuel


public static <T> void setTopItem(List<T> t, int position){
    t.add(0, t.remove(position));
}
like image 32
Mines Valderama-Hababag Hernan Avatar answered Nov 15 '22 21:11

Mines Valderama-Hababag Hernan


To move the original item to the top of the original list:

public static <T> void rearrange(List<T> items, T input){
    int i = items.indexOf(input);
    if(i>=0){
        items.add(0, items.remove(i));
    }
}
like image 36
Navigateur Avatar answered Nov 15 '22 21:11

Navigateur