Simplest Solution (for a beginner)
The ArrayList and List default add() behavior by definition, adds to the end of the list. So:-
listToReorder.add(string)
You will need to remove it from it's original position though, so don't use a for-each loop, use an index, then when you find it:-
listToReorder.remove(i);
...before re-adding it to the end, so:-
for (int i=0; i<listToReorder.size(); i++){
String item = listToReorder.get(i);
//NOTE: '==true' isn't required if the method returns a boolean
if(checkIfWordIsInTextFile(item)){
//As per @rishi007bansod suggestion: If we remove an item, then the next item will be shifted into this index & effectively skipped. Therefore we want the index not to change this time around so decrement i after usage
listToReorder.remove(i--);
listToReorder.add(item);
}
}
Other options
- You could create a new temporary list and recreate the list in the order you want but that makes for complicated code, as per @Andriy Kryvtsuns answer. The other problem with this is that you don't know what implementation of
List
was passed in, creating a whole list could be inefficient if, say, a LinkedList
was passed it and remove()
can run faster than linear time.
More advanced options
You could use a for-each loop (like @Ash French) but you'd need to use an Iterator
as for-each loops restrict you from editing Collections you are looping over
You could get all Java 8 and use a lambda, as per @Mad Matts elegant solution