Moving Items Around in an Arraylist

Moving items around in an ArrayList

I came across this old question in my search for an answer, and I thought I would just post the solution I found in case someone else passes by here looking for the same.

For swapping 2 elements, Collections.swap is fine. But if we want to move more elements, there is a better solution that involves a creative use of Collections.sublist and Collections.rotate that I hadn't thought of until I saw it described here:

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate%28java.util.List,%20int%29

Here's a quote, but go there and read the whole thing for yourself too:

Note that this method can usefully be applied to sublists to move one
or more elements within a list while preserving the order of the
remaining elements. For example, the following idiom moves the element
at index j forward to position k (which must be greater than or equal
to j):

Collections.rotate(list.subList(j, k+1), -1);

moving elements in arraylist java

In terms of lines of code, it is easiest simply to remove the element from the list and reinsert it at the new position:

list.add(toPos, list.remove(fromPos));

However, this isn't necessarily the most efficient way to do it, since it requires all of the elements in the array list to be shifted down by the remove, and shifted up by the insert.

You can do it more efficiently by explicitly shifting all of the elements in-place:

Integer fromValue = list.get(fromPos);
int delta = fromPos < toPos ? 1 : -1;
for (int i = fromPos; i != toPos; i += delta) {
list.set(i, list.get(i + delta));
}
list.set(toPos, fromValue);

Moving several items in an ArrayList

You could wrap your list in a reorderable list and implement your reordering through that - at least you wouldn't need to hack the main list. It would maintain the order in an array of ints which you can then move around at will. You could even maintain the same data in several different orders if you like.

public static class OrderedList<T> extends AbstractList<T> {

// The list I proxy.
private final List<T> it;
// The order.
private final int[] order;

public OrderedList(List<T> wrap) {
it = wrap;
order = new int[it.size()];
// Initially the same order.
for (int i = 0; i < order.length; i++) {
order[i] = i;
}
}

@Override
public T get(int index) {
return it.get(order[index]);
}

@Override
public int size() {
return it.size();
}

// TODO - Only moves up! Breaks on a down move.
public void move(int start, int length, int to) {
int[] move = new int[length];
// Copy it out.
System.arraycopy(order, start, move, 0, length);
// Shift it down.
System.arraycopy(order, start + length, order, start, to - start);
// Pull it back in.
System.arraycopy(move, 0, order, to, length);

}
}

public void test() {
List<String> t = Arrays.asList("Zero", "One", "Two", "Three", "Four", "Five");
OrderedList<String> ordered = new OrderedList(t);
System.out.println(ordered);
ordered.move(1, 2, 3);
System.out.println(ordered);
}

prints

[Zero, One, Two, Three, Four, Five]
[Zero, Three, Four, One, Two, Five]

Alternatively - use Collections.rotate and work out what sub-list should be rotated which way to achieve your move.

move one element after another element in arraylist

Thank you all, I finally used this code:

 public static void moveElementAfter(ArrayList<String> arrayList,String src, String dst) {
int sourceIndex = arrayList.indexOf(src);
int destIndex = arrayList.indexOf(dst);
// copy source element after destination
arrayList.add(destIndex + 1, src);

if (sourceIndex < destIndex) {
// * the source element is moved forward in the array list
// remove the source element
arrayList.remove(sourceIndex);
} else {
// * the source element is moved backward in the array list
// remove the source element
int sourceLastIndex = arrayList.lastIndexOf(src);
arrayList.remove(sourceLastIndex);
}// end if
System.out.println(arrayList);
}// end method

Demo

System.out.println("move A after C");
ArrayList<String> arrayList1 = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
moveElementAfter(arrayList1, "A", "C");

System.out.println("move C after A");
ArrayList<String> arrayList2 = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
moveElementAfter(arrayList2, "C", "A");

Output

[B, C, A, D]
[A, C, B, D]

Moving ArrayList element to the last position in the List?

Simplest Solution (for a beginner)

The ArrayList and List default add() behavior by definition, adds to the end of the list. So:-

listToReorder.add(string)

You will need to remove it from it's original position though, so don't use a for-each loop, use an index, then when you find it:-

listToReorder.remove(i);

...before re-adding it to the end, so:-

for (int i=0; i<listToReorder.size(); i++){
String item = listToReorder.get(i);

//NOTE: '==true' isn't required if the method returns a boolean
if(checkIfWordIsInTextFile(item)){
//As per @rishi007bansod suggestion: If we remove an item, then the next item will be shifted into this index & effectively skipped. Therefore we want the index not to change this time around so decrement i after usage
listToReorder.remove(i--);
listToReorder.add(item);
}
}

Other options

  • You could create a new temporary list and recreate the list in the order you want but that makes for complicated code, as per @Andriy Kryvtsuns answer. The other problem with this is that you don't know what implementation of List was passed in, creating a whole list could be inefficient if, say, a LinkedList was passed it and remove() can run faster than linear time.

More advanced options

  • You could use a for-each loop (like @Ash French) but you'd need to use an Iterator as for-each loops restrict you from editing Collections you are looping over

  • You could get all Java 8 and use a lambda, as per @Mad Matts elegant solution

How to move specific item in array list to the first item

What you want is a very expensive operation in an ArrayList. It requires shifting every element between the beginning of the list and the location of C down by one.

However, if you really want to do it:

int index = url.indexOf(itemToMove);
url.remove(index);
url.add(0, itemToMove);

If this is a frequent operation for you, and random access is rather less frequent, you might consider switching to another List implementation such as LinkedList. You should also consider whether a list is the right data structure at all if you're so concerned about the order of elements.

Move element from one array list to another java

If you want to move a specific item :

moveSellableItem(List<SellableItem> source, SellableItem item, List<SellableItem> destination){
destination.add(item);
source.remove(item);
}

If you want to move all item with a specific parameter (price in example) :

moveSellableItemWithPrice(List<SellableItem> source, double price, List<SellableItem> destination)
{
var itemsToMove = new ArrayList<SellableItem>();
for(SellableItem item : source){
if(item.price == price) {
itemsToMove.add(item);
}
}
source.removeAll(itemsToMove);
destination.addAll(itemsToMove);
}

In addition, you can use a lambda instead of the foreach loop :

From Java 8 :
var itemsToMove = source.stream().filter(i -> i.price == price).collect(Collectors.toList());

From Java 16 :
var itemsToMove = source.stream().filter(i -> i.price == price).toList();

How To move Items Between ArrayLists? Java

on item drop:

Tomato tomato = new Tomato();
worldInventory.add(tomato);

on pickup:

worldInventory.remove(tomato);
inventory.add(tomato);

on equip:

inventory.remove(tomato);
equipped.add(tomato);

Just wondering why do you need equipped ArrayList ?

you can have a boolean flag inside your WorldObject ( boolean equipped = false)
and just set it to true, when the item is equipped.

Moving elements from one ArrayList to another

Keeping track of the index where to insert the element you just removed:

int insertIndex = target;
for (int i = 0; i < n; i++) {
if (fromList.size() > start) {
String removed = fromList.remove(start);
toList.add(insertIndex, removed);
insertIndex++;
}
}


Related Topics



Leave a reply



Submit