Moving list items

I have a list of objects and I want to do some kind of operation on the list in such a way that a particular object should be shifted to list position 0, and the object at position 0 will have a shifted object. the diagram is shown below.

enter image description here

the list looks like this

final List<Object> list= new ArrayList<Object>();

      

Currently I have made two temporary lists as

final List<Object> temp1= new ArrayList<Object>();
    final List<Object> temp2= new ArrayList<Object>();

      

to perform the operation, I start a loop and on a specific condition, adding an object to temp1, adding to temp2, something like the following:

for (int i = 0; i < 5; i++) {

                if (i==3) {

                    temp1.add(i);

                } else {
                    temp2.add(i);
                }
            }

      

and finally doing

list.addAll(temp1);
            list.addAll(temp2);

      

how to do the same logic in redundant and efficient steps instead of using temporary lists.

+3


source to share


2 answers


Use this swap method :



Collections.swap(List<?> list, int i, int j);

      

+11


source


Try this code:



Object temp = list.get(0);
list.set(0, list.get(3));
list.set(3, temp);

      

+6


source







All Articles