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.
How to move specific item in array list to the first item in Java? To move an item from an ArrayList and add it to the first position you need to - Get the position (index) of the item using the indexOf () method of the ArrayList class. Remove it using the remove () method of the ArrayList class.
Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.
Get the first element of ArrayList with use of get (index) method by passing index = 0. Get the last element of ArrayList with use of get (index) method by passing index = size – 1.
Create an ArrayList object. Add elements to it. Sort it using the sort () method of the Collections class. Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value.
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)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With