Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pop items from a collection in Java?

Is there a method in JDK or apache commons to "pop" a list of elements from a java.util.List? I mean, remove the list of elements and return it, like this method:

public Collection pop(Collection elementsToPop, Collection elements) {

  Collection popped = new ArrayList();

  for (Object object : elementsToPop) {
    if (elements.contains(object)) {
      elements.remove(object);
      popped.add(object);
    }
  }

  return popped;
}
like image 948
The Student Avatar asked Jun 08 '10 15:06

The Student


People also ask

How do you remove a specific item from a collection in Java?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

What does remove () do in Java?

The remove() method is used to remove an element at a specified index from ArrayList. Shifts any subsequent elements to the left (subtracts one from their indices).

Can I remove an element from a list while iterating Java?

Even though java. util. ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.

Which allows the removal of elements from a collection *?

➢ Iterator method remove removes the current element from a Collection.


2 Answers

If you're looking for a stack-like structure I suggest accepting a Deque (LinkedList is the most common implementation) instead of a Collection.

If you don't actually need to treat it as a stack, just get an iterator from the Collection and use the remove() method:

for (Iterator<SomeType> it = elements.iterator(); it.hasNext(); ) {
    SomeType e = it.next();
    it.remove();
    popped.add(e);
}

Do note that remove is an optional operation, and some implementations may throw an UnsupportedOperationException (for example, the iterator returned by a Collection from Collections.unmodifiable...() will).

Edit: After looking more closely at your question, I think you just need this:

elements.removeAll(elementsToRemove);

If your main point is you need to know exactly which elements were actually popped, I think you're stuck with your original code.

like image 113
Mark Peters Avatar answered Oct 16 '22 04:10

Mark Peters


There is no such method in the standard JDK-provided methods. Apache Commons provides the ListUtils.subtract() method.

Edit: As other answerers have noted, your use of the term pop is nonstandard. Usually,

The pop operation removes an item from the top of [a stack]

Wikipedia has a nice description of stacks.

like image 32
Pops Avatar answered Oct 16 '22 02:10

Pops