define the first element of a list


I have the following List:

private String[] myArray = new String[]{"A","B","C"} ;
List myList = new ArrayList();
for (int i = 0; i < myArray.length; i++) {

There is a method that returns an element of the myList

String returnValue=myMethod();

returnValue could be A or B or C

returnValue should be the first element of the List

myList.add(0, returnValue);

Issue is if returnValue="B" ,myList becomes {"B","B","C"}.

I could explicitly remove the returnValue and add it again to myList. But it seems rather redundant ,can anybody suggest a better design approach.

My Required Result would be {"B","A","C"}

As far as I understood, you want the returnValue to become the first element of the List, i.e. change the order. This can be achieved by using:

Collections.swap(myList, 0, myList.indexOf(returnValue));

Since this does not use adding nor removing, it allows to simplify your entire code:

List<String> myList = Arrays.asList("A","B","C");
String returnValue=myMethod();
Collections.swap(myList, 0, myList.indexOf(returnValue));

Note that this changes the order of the remaining elements. If you want to retain the order of all elements but the one you move to the front of the list (like remove followed by add would do) you need to use rotate:

List<String> myList = Arrays.asList("A","B","C");
String returnValue=myMethod();
Collections.rotate(myList.subList(0, myList.indexOf(returnValue)+1), 1);

But using swap will be faster on large lists, so if you don’t need the remaining elements to retain the original order, using swap is recommended.