How to move the first element of arraylist to the last position?

my code will go to the last arraylist:

 if (listItem.get(listItem.size() - 1).SortNo > 0) {
                    while (listItem.get(0).SortNo == 0) {

                        DTO_NightClinic dt = listItem.get(0);
                        listItem.remove(0);
                        listItem.add(dt);
                    }
                }

But ordinary listItem.remove(0);it does not work. and the first element still exists in the first position of the arraylist.

+4
source share
3 answers
Collections.rotate(list, -1);

Just use turn with -1and it will do what you want

Input:

1, 2, 3, 4

Output:

2, 3, 4, 1

More on Collection # rotate (java.util.List, int)

+8
source

It may Collections.rotate()seem like an acceptable solution, but some require an advanced task ... see sourceCollections.roatate()

public static void rotate(List<?> lst, int dist) {
      ...............
        reverse(sublist1);
        reverse(sublist2);
        reverse(list);
}

Collections.reverse() opearion, .

, , , , ...

    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    for (int i = 1; i < 5; i++) {
        arrayList.add(Integer.valueOf(i));
    }
    System.out.println(arrayList.toString());
    // prints [1, 2, 3, 4]

    Integer removedItem = arrayList.remove(0);
    arrayList.add(removedItem); // adds to the end of the List
    System.out.println(arrayList.toString());
    // prints [2, 3, 4, 1]
+2
Collections.rotate(list, -1);

/ ...................................

+1
source

All Articles