user339108 user339108 - 5 months ago 21
Java Question

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

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"

Answer
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.addAll(items.subList(0, index));
    copy.add(0, items.get(index));
    copy.addAll(items.subList(index + 1, items.size()));
  } else {
    copy = new ArrayList<T>(items);
  }
  return copy;
}