From 2a0f86a94d1a6808d12f04d6bf2d5ef8257a33ab Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 1 Nov 2024 16:11:38 -0400 Subject: [PATCH] Add FilterIterator.removeNext() #564 --- src/changes/changes.xml | 1 + .../collections4/iterators/FilterIterator.java | 12 ++++++++++++ .../iterators/FilterIteratorTest.java | 17 ++++++++++++++++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 2843c6265..81c2f430e 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -59,6 +59,7 @@ Add org.apache.commons.collections4.IteratorUtils.chainedIterator(Iterator<? extends Iterator<? extends E>>). Add ArrayListValuedLinkedHashMap #560. Add missing test AbstractIteratorTest.testForEachRemaining(). + Add FilterIterator.removeNext() #564. Bump org.apache.commons:commons-parent from 71 to 78 #534, #545, #550 #555, #566. Update bloom filter documentation #508. diff --git a/src/main/java/org/apache/commons/collections4/iterators/FilterIterator.java b/src/main/java/org/apache/commons/collections4/iterators/FilterIterator.java index 98047fe66..e9872a2b1 100644 --- a/src/main/java/org/apache/commons/collections4/iterators/FilterIterator.java +++ b/src/main/java/org/apache/commons/collections4/iterators/FilterIterator.java @@ -141,6 +141,18 @@ public class FilterIterator implements Iterator { iterator.remove(); } + /** + * Returns the next item and removes it from the iterator. + * + * @return the next item from the iterator. + * @since 4.5.0-M3 + */ + public E removeNext() { + final E result = next(); + remove(); + return result; + } + private Predicate safePredicate(final Predicate predicate) { return predicate != null ? predicate : TruePredicate.truePredicate(); } diff --git a/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java index f8ef27c6f..582e79a4d 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java @@ -172,6 +172,22 @@ public class FilterIteratorTest extends AbstractIteratorTest { assertTrue(actual.isEmpty()); } + @Test + public void testRemoveNext() { + final FilterIterator iter = makeObject(); + final E i = iter.removeNext(); + assertFalse(list.contains(i)); + final List actual = new ArrayList<>(); + iter.forEachRemaining(actual::add); + assertEquals(list, actual); + } + + @Test + public void testRemoveNextEmpty() { + final FilterIterator empty = makeEmptyIterator(); + assertThrows(NoSuchElementException.class, empty::removeNext); + } + @Test public void testRepeatedHasNext() { for (int i = 0; i <= array.length; i++) { @@ -188,7 +204,6 @@ public class FilterIteratorTest extends AbstractIteratorTest { verifyNoMoreElements(); } - @Test public void testReturnValues() { verifyElementsInPredicate(ArrayUtils.EMPTY_STRING_ARRAY);