How to Remove Element from Arraylist by Checking Its Value

How to remove element from ArrayList by checking its value?

In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):

 a.remove(1);       // indexes are zero-based

Or, you can remove the first occurence of your string:

 a.remove("acbd");  // removes the first String object that is equal to the
// String represented by this literal

Or, remove all strings with a certain value:

 while(a.remove("acbd")) {}

It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using remove with an object that is equal to the one you want to delete.

In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:

 List<MyBean> deleteCandidates = new ArrayList<>();
List<MyBean> myBeans = getThemFromSomewhere();

// Pass 1 - collect delete candidates
for (MyBean myBean : myBeans) {
if (shallBeDeleted(myBean)) {
deleteCandidates.add(myBean);
}
}

// Pass 2 - delete
for (MyBean deleteCandidate : deleteCandidates) {
myBeans.remove(deleteCandidate);
}

Remove items from ArrayList with certain value

If you are going to be using an ArrayList, the the only way is to go through the entire list, looking at each person, and seeing it their id number is 114. For larger datasets, this is not going to efficient and should be avoided.

If you can change your data structure, then some sort of Map would be better (HashMap is typically a good choice). You could have the id number as a "key" and then associate it with each person. Later you can query the Map by key. The con is you can only have one value as a key, so you can't have say both name and id number keys

Edit:

An more efficient way to do use an ArrayList would be to keep it sorted by id number. Then you can use something like Collections.binarySearch() to quickly access the elements by id number. The con is is that it is expensive to remove from/insert into a sorted array, as everything greater the element has to be moved. So if you are going to be doing relatively few changes compared to the number of reads, this might be viable

How to delete specific element from array list

The problem you have right now is you're just removing an element from the list's index based on user input while you should make sure list is of that size. Second thing, You can't remove an element from the list while browsing it via the forEach loop, you would get a ConcurrentModificationException , read concurrentModificationException. The way to do it would be using an iterator, check

Iterator<Passenger> itr = passengerList.iterator();
while (itr.hasNext()){
Passenger p = itr.next();
if (id == p.getId()) {
itr.remove();
break;
}
}

How can I remove a specific object from an arrayList and how can I check if it contains this object?

You will need to add a .equals method to the Item class so ArrayLists know how to compare two different objects together. While we are at it we should add a hashCode method as well. This is mainly useful for Sets but always good to have it as a backup in case we need it.

We can use the .indexOf(Item) method to get the position of an object in the list. If the number returns if -1. Then it's not in the list. If it is 0 or greater then it's in there and we can use the index to remove the item.

public class Item{
private String type;

public Item(String type){
this.type = type;
}

public String getType(){
return type;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Item))
return false;
Item other = (Item) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}

Now that we have a .equals and hashcode. We can now compare them in the ArrayList.

ArrayList<Item> itemList = new ArrayList<Item>();

// Fill the list
itemList.add(new Item("Banana"));
itemList.add(new Item("Toaster"));
itemList.add(new Item("Screw Driver"));

Item item = new Item("Hand Grenade");
itemList.add(item);

int index = itemList.indexOf(item);
if( index != -1 ){
System.out.println("The item is in index " + index);

// Remove the item and store it in a variable
Item removedItem = itemList.remove(index);
System.out.println("We removed " + removedItem.getType() + " from the list.");
}

Remove objects from an ArrayList based on a given criteria

You must use an Iterator to iterate and the remove function of the iterator (not of the list) :

Iterator<Pulse> iter = pulseArray.iterator();
while (iter.hasNext()) {
Pulse p = iter.next();
if (p.getCurrent()==null) iter.remove();
}

Note that the Iterator#remove function is said to be optionnal but it is implemented by the ArrayList's iterator.

Here's the code of this concrete function from ArrayList.java :

765         public void remove() {
766 if (lastRet < 0)
767 throw new IllegalStateException();
768 checkForComodification();
769
770 try {
771 ArrayList.this.remove(lastRet);
772 cursor = lastRet;
773 lastRet = -1;
774 expectedModCount = modCount;
775 } catch (IndexOutOfBoundsException ex) {
776 throw new ConcurrentModificationException();
777 }
778 }
779
780 final void checkForComodification() {
781 if (modCount != expectedModCount)
782 throw new ConcurrentModificationException();
783 }
784 }

The expectedModCount = modCount; line is why it won't throw an exception when you use it while iterating.

Removing elements from ArrayList

This however leaves "empty spaces" in my list.

No, it doesn't. It removes entries from the list completely. Other elements are moved appropriately. What it does do with the way you've written is skip the check for the next entry... because that will have "shuffled down" to be element i, but you'll next look at element i + 1.

One simple way to avoid this is to work backwards instead:

for (int i = myList.size() - 1; i >= 0; i--) {
if (myList.get(i).contains("foo")) {
myList.remove(i);
}
}

Or use an iterator as noted in other answers, of course. Both will work - the above code may be slightly more efficient if you're removing multiple entries, however, as there'll be less to shift by the time you get to the start. It's unlikely that that will be significant.

It's unfortunate that in order to use the iterator solution you have to use the iterator explicitly - you can't remove from a collection while using an enhanced for loop.



Related Topics



Leave a reply



Submit