I have a list of Strings and I am required to ensure that one particular element is always in the firt position in the list. Here is an illustration. Assuming that my list contains [sicav action, droits de souscription, famille action, fcp actions]. I am required to make sure that 'famille action' is always at the first position before a further processing on the list occurs.
Here is how I did it:
/**
* Force this list to alway keep the constrained value on top
* @param liste
* @param constraint
*/
public void doConstrainList(List<String> liste, String constraint) {
System.out.println("List initial state: " + liste);
if (!liste.contains(constraint)) {
return;
}
int indexToProcess = liste.indexOf(constraint);
String keeper = constraint;
liste.remove(indexToProcess);
liste.add(0, keeper);
System.out.println("List state after processing:" + liste);
}
When I call this method with the list example mentionned above for the same constraint value I obtain the following result
So this is working as expected, but I would like to know if there is a better way to do it. For chances are the list will keep growing in size and I would not like this method to be time consumming. I am using Java 1.6 and I can't use newer Java version. Thanks for any help