diff --git a/src/java/org/apache/commons/collections/ListUtils.java b/src/java/org/apache/commons/collections/ListUtils.java index 8cfec1380..64f8acab8 100644 --- a/src/java/org/apache/commons/collections/ListUtils.java +++ b/src/java/org/apache/commons/collections/ListUtils.java @@ -42,6 +42,7 @@ import org.apache.commons.collections.list.UnmodifiableList; * @author Stephen Colebourne * @author Neil O'Toole * @author Matthew Hawthorne + * @author Dave Meikle */ public class ListUtils { @@ -410,4 +411,26 @@ public class ListUtils { return FixedSizeList.decorate(list); } + /** + * Finds the first index in the given List which matches the given predicate. + *
+ * If the input List or predicate is null, or no element of the List
+ * matches the predicate, -1 is returned.
+ *
+ * @param list the List to search, may be null
+ * @param predicate the predicate to use, may be null
+ * @return the first index of an Object in the List which matches the predicate or -1 if none could be found
+ */
+ public static int indexOf(List list, Predicate predicate) {
+ if (list != null && predicate != null) {
+ for (int i = 0; i < list.size(); i++) {
+ Object item = list.get(i);
+ if (predicate.evaluate(item)) {
+ return i;
+ }
+ }
+ }
+ return -1;
+ }
+
}
diff --git a/src/test/org/apache/commons/collections/TestListUtils.java b/src/test/org/apache/commons/collections/TestListUtils.java
index 47461bbc6..b0671e1e7 100644
--- a/src/test/org/apache/commons/collections/TestListUtils.java
+++ b/src/test/org/apache/commons/collections/TestListUtils.java
@@ -33,6 +33,7 @@ import org.apache.commons.collections.list.PredicatedList;
* @author Stephen Colebourne
* @author Neil O'Toole
* @author Matthew Hawthorne
+ * @author Dave Meikle
*/
public class TestListUtils extends BulkTest {
@@ -172,5 +173,21 @@ public class TestListUtils extends BulkTest {
fail("expecting NullPointerException");
} catch(NullPointerException npe) {} // this is what we want
}
+
+ /**
+ * Tests the indexOf
method in ListUtils
class..
+ */
+ public void testIndexOf() {
+ Predicate testPredicate = PredicateUtils.equalPredicate("d");
+ int index = ListUtils.indexOf(fullList, testPredicate);
+ assertEquals(d, fullList.get(index));
+
+ testPredicate = PredicateUtils.equalPredicate("de");
+ index = ListUtils.indexOf(fullList, testPredicate);
+ assertTrue(index == -1);
+
+ assertEquals(ListUtils.indexOf(null,testPredicate), -1);
+ assertEquals(ListUtils.indexOf(fullList, null), -1);
+ }
}