Add a filter function to CollectionUtils
This is generally useful, and specifically useful in
NetworkRanker
Test: Used in NetworkRanker, ConnectivityServiceTest
Change-Id: I896e7e5bcb2931ce43a5b88967bfd6fcd1de0ce2
diff --git a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
index 2223443..f2afc75 100644
--- a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
@@ -20,6 +20,7 @@
import android.annotation.Nullable;
import android.util.SparseArray;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Predicate;
@@ -148,4 +149,21 @@
}
return -1;
}
+
+ /**
+ * Returns a new collection of elements that match the passed predicate.
+ * @param source the elements to filter.
+ * @param test the predicate to test for.
+ * @return a new collection containing only the source elements that satisfy the predicate.
+ */
+ @NonNull private static <T> ArrayList<T> filter(@NonNull final Collection<T> source,
+ @NonNull final Predicate<T> test) {
+ final ArrayList<T> matches = new ArrayList<>();
+ for (final T e : source) {
+ if (test.test(e)) {
+ matches.add(e);
+ }
+ }
+ return matches;
+ }
}