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"
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;
}
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;
}
public static <T> void setTopItem(List<T> t, int position){
t.add(0, t.remove(position));
}
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With