Nathan Egge requested a ListUtils.indexOf(List, Predicate) method in COLLECTIONS-235. Applying Dave Meikle's patch.
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/trunk@637505 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
8a5d3acab8
commit
eb9cff359c
|
@ -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.
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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 <code>indexOf</code> method in <code>ListUtils</code> 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue