Remove Item from ArrayList

JavaArraylist

Java Problem Overview


I have an ArrayList suppose list, and it has 8 items A-H and now I want to delete 1,3,5 position Item stored in int array from the list how can I do this.

I am trying to do this with

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");
				
int i[] = {1,3,5};
				
for (int j = 0; j < i.length; j++) {
    list.remove(i[j]);
}

But after first item deleted positioned of array is changed and in the next iterate it deletes wrong element or give exception.

Java Solutions


Solution 1 - Java

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

Solution 2 - Java

You can remove elements from ArrayList using ListIterator,

ListIterator listIterator = List_Of_Array.listIterator();

 /* Use void remove() method of ListIterator to remove an element from List.
     It removes the last element returned by next or previous methods.
 */
listIterator.next();

//remove element returned by last next method
listIterator.remove();//remove element at 1st position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 3rd position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 5th position

Solution 3 - Java

 public void DeleteUserIMP(UserIMP useriamp) {
	   synchronized (ListUserIMP) {
		    if (ListUserIMP.isEmpty()) {
			System.out.println("user is empty");
		}  else {
			Iterator<UserIMP> it = ListUserIMP.iterator();
			while (it.hasNext()) {
				UserIMP user = it.next();
				if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
					it.remove();
					System.out.println("remove it");
				}
			}
			// ListUserIMP.remove(useriamp);

			System.out.println(" this user removed");
		}
		Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
		// System.out.println("This user Deleted " + Constants.MESSAGE_OK);

	}
}

Solution 4 - Java

As mentioned before

iterator.remove()

is maybe the only safe way to remove list items during the loop.

For deeper understanding of items removal using the iterator, try to look at this thread

Solution 5 - Java

I assume the array i is ascend sorted, here is another solution with Iterator, it is more generic:

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

Iterator<String> itr = list.iterator();
int pos = 0;
int index = 0;
while( itr.hasNext() ){
    itr.next();
    if( pos >= i.length ){
        break;
    }
    if( i[pos] == index ){
        itr.remove();
        pos++;
    }
    
    index++;
}

Solution 6 - Java

String[] mString = new String[] {"B", "D", "F"};

for (int j = 0; j < mString.length-1; j++) {
        List_Of_Array.remove(mString[j]);
}

Solution 7 - Java

How about this? Just give it a thought-

import java.util.ArrayList;

class Solution
{
        public static void main (String[] args){
        	
        	 ArrayList<String> List_Of_Array = new ArrayList<String>();
             List_Of_Array.add("A");
             List_Of_Array.add("B");
             List_Of_Array.add("C");
             List_Of_Array.add("D");
             List_Of_Array.add("E");
             List_Of_Array.add("F");
             List_Of_Array.add("G");
             List_Of_Array.add("H");

             int i[] = {1,3,5};

             for (int j = 0; j < i.length; j++) {
                 List_Of_Array.remove(i[j]-j);
             }
             
             System.out.println(List_Of_Array);

        }
        
        
}

And the output was-

[A, C, E, G, H]

Solution 8 - Java

Try it this way,

ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");

int i[] = {5,3,1};

for (int j = 0; j < i.length; j++) {
    List_Of_Array.remove(i[j]);
}

Solution 9 - Java

If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="

		List_Of_Array1.addAll(List_Of_Array);

Solution 10 - Java

remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.

Means if a arraylist contains {20,15,30,40}

I have called the method: arraylist.remove(1)

then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.

For this reason you have to delete higher index item of arraylist first.

So..for your given situation..the code will be..

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

Solution 11 - Java

if you need to remove end item in list can use this code

 if(yourList.size() != 0){
   yourList.remove(yourList.size()-1);
 }

or maybe you need to remove a time after select item in list

if(selected){// boolean for checked add or remove
   yourList.add(position , id); // add to list by position can use your list position
}else{
   if(yourList.size() != 0){ 
   yourList.remove(position);
 }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKrishnakant DalalView Question on Stackoverflow
Solution 1 - JavaAlex LockwoodView Answer on Stackoverflow
Solution 2 - JavaJainendraView Answer on Stackoverflow
Solution 3 - Javauser1931357View Answer on Stackoverflow
Solution 4 - Javashimon001View Answer on Stackoverflow
Solution 5 - JavaDàChúnView Answer on Stackoverflow
Solution 6 - JavaMohammed Azharuddin ShaikhView Answer on Stackoverflow
Solution 7 - JavasgowdView Answer on Stackoverflow
Solution 8 - JavaKhanView Answer on Stackoverflow
Solution 9 - JavaRahul GuptaView Answer on Stackoverflow
Solution 10 - JavaAvijit KarmakarView Answer on Stackoverflow
Solution 11 - JavaMohammad No3ratiiView Answer on Stackoverflow