mum
mum

Reputation: 1645

How move first item of arraylist to last position?

my code move to 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 common listItem.remove(0); it not working. and first item still exist at first position of arraylist.

Upvotes: 6

Views: 3709

Answers (3)

Gopal Gopi
Gopal Gopi

Reputation: 11131

Perhaps Collections.rotate() seems to feasible solution but it is some want extended task... see the source of Collections.roatate()

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

it iterates through all Items of List and applies Collections.reverse() opearion thus consumes some time.

and here, as you are simply want to remove the first item from List and add it to the tail of List, You can do a simple trick like below sample...

    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]

Upvotes: 1

Digvesh Patel
Digvesh Patel

Reputation: 6533

Collections.rotate(list, -1);

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

Upvotes: 1

Narendra Pathai
Narendra Pathai

Reputation: 41955

Collections.rotate(list, -1);

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

Input:

1, 2, 3, 4

Output:

2, 3, 4, 1

For more on Collections#rotate(java.util.List,int)

Upvotes: 10

Related Questions