Skip to content

Instantly share code, notes, and snippets.

@nirodg
Created March 25, 2018 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirodg/d099fd6d6c8bce5f6bae8be9ad777011 to your computer and use it in GitHub Desktop.
Save nirodg/d099fd6d6c8bce5f6bae8be9ad777011 to your computer and use it in GitHub Desktop.
Mimic the sortable jquery functionality https://jqueryui.com/sortable/
public static <T> List<T> sortItem(List<T> sortList, int moveFrom, int moveTo) {
if (moveFrom == moveTo) {
// do nothing
return null;
}
boolean isLastPosition = (sortList.size() == moveTo + 1);
T currentElement = sortList.get(moveFrom);
//remove element from list
sortList.remove(currentElement);
List<T> sortedList = new ArrayList<>(sortList.size());
for (int pos = 0; pos < sortList.size(); pos++) {
if (pos == moveTo) {
// add item to the willing position
sortedList.add(currentElement);
// add the one is supposed to be the next so we won't miss it.
sortedList.add(sortList.get(pos));
} else {
sortedList.add(sortList.get(pos));
}
}
if (isLastPosition) {
sortedList.add(currentElement);
}
return sortedList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment