Add CollectionUtils.indexOf
indexOf() is based on the current any() implementation, but gives more
flexibility as the caller can know the position of the found element.
Bug: 174541037
Test: atest NetworkStaticLibTests
Change-Id: I1d679b8369aeee359516bb5ca4275c744a606c3a
diff --git a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
index e5bb58d..115f19d 100644
--- a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
@@ -76,15 +76,26 @@
return true;
}
+
/**
* @return True if any element satisfies the predicate, false otherwise.
* Note that means this always returns false for empty collections.
*/
public static <T> boolean any(@NonNull Collection<T> elem, @NonNull Predicate<T> predicate) {
+ return indexOf(elem, predicate) >= 0;
+ }
+
+ /**
+ * @return The index of the first element that matches the predicate, or -1 if none.
+ */
+ @Nullable
+ public static <T> int indexOf(@NonNull Collection<T> elem, @NonNull Predicate<T> predicate) {
+ int idx = 0;
for (final T e : elem) {
- if (predicate.test(e)) return true;
+ if (predicate.test(e)) return idx;
+ idx++;
}
- return false;
+ return -1;
}
/**
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt b/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
index 0007742..0886426 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
@@ -20,6 +20,7 @@
import androidx.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
+import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@@ -40,6 +41,15 @@
}
@Test
+ fun testIndexOf() {
+ assertEquals(4, CollectionUtils.indexOf(listOf("A", "B", "C", "D", "E")) { it == "E" })
+ assertEquals(0, CollectionUtils.indexOf(listOf("A", "B", "C", "D", "E")) { it == "A" })
+ assertEquals(1, CollectionUtils.indexOf(listOf("AA", "BBB", "CCCC")) { it.length >= 3 })
+ assertEquals(1, CollectionUtils.indexOf(listOf("AA", null, "CCCC")) { it == null })
+ assertEquals(1, CollectionUtils.indexOf(listOf(null, "CCCC")) { it != null })
+ }
+
+ @Test
fun testAll() {
assertFalse(CollectionUtils.all(listOf("A", "B", "C", "D", "E")) { it != "E" })
assertTrue(CollectionUtils.all(listOf("A", "B", "C", "D", "E")) { it != "F" })