Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,26 @@ public static <T> T get(Iterator<T> iterator, int index) {
Objects.requireNonNull(iterator, "Iterator must not be null");
return org.apache.commons.collections4.IteratorUtils.get(iterator, index);
}

/**
* Returns the last element in the given iterator.
* <p>
* This method consumes the entire iterator to find the last element.
* <p>
*
* @param <T> the type of elements in the iterator
* @param iterator the iterator to get the last element from, must not be null
* @return the last element in the iterator
* @throws NullPointerException if the iterator is null
* @throws NoSuchElementException if the iterator is empty
*/
public static <T> T getLast(Iterator<T> iterator) {
Objects.requireNonNull(iterator, "Iterator must not be null");
while (true) {
T currentElement = iterator.next();
if (!iterator.hasNext()) {
return currentElement;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -365,4 +365,53 @@ public String toString() {
TestObject result = IteratorUtils.get(data.iterator(), 1);
Assert.assertEquals("obj2", result.toString());
}

@Test
public void testGetLastWithMultipleElements() {
Iterator<String> iterator = Arrays.asList("one", "two", "three").iterator();
Assert.assertEquals("three", IteratorUtils.getLast(iterator));
Assert.assertFalse(iterator.hasNext());
}

@Test
public void testGetLastWithSingleElement() {
Iterator<Integer> intIterator = List.of(1).iterator();
Assert.assertEquals(Integer.valueOf(1), IteratorUtils.getLast(intIterator));
Assert.assertFalse(intIterator.hasNext());
}

@Test(expected = NullPointerException.class)
public void testGetLastWithNullIterator() {
IteratorUtils.getLast(null);
}

@Test(expected = NoSuchElementException.class)
public void testGetLastWithEmptyIterator() {
IteratorUtils.getLast(Collections.emptyIterator());
}

@Test
public void testGetLastWithDifferentTypes() {
class TestObject {
private final String value;

TestObject(String value) {
this.value = value;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestObject that = (TestObject) o;
return value.equals(that.value);
}
}

TestObject obj1 = new TestObject("first");
TestObject obj2 = new TestObject("last");
Iterator<TestObject> objectIterator = Arrays.asList(obj1, obj2).iterator();
Assert.assertEquals(obj2, IteratorUtils.getLast(objectIterator));
Assert.assertFalse(objectIterator.hasNext());
}
}
Loading