Skip to content

Commit

Permalink
ArrayUtils: Added filter(predicate) method
Browse files Browse the repository at this point in the history
  • Loading branch information
reportmill committed Sep 30, 2021
1 parent c3a381b commit 024f25a
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/snap/util/ArrayUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package snap.util;
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Predicate;

/**
* A collection of array utility methods.
Expand Down Expand Up @@ -389,4 +390,40 @@ public static void reverse(Object[] anArray)
anArray[j] = temp;
}
}

/**
* Returns a filtered array for given original and Predicate (or original if all satisfy).
*/
public static <T> T[] filter(T[] anArray, Predicate<? super T> aPredicate)
{
T[] array = anArray;
int length = 0;

// Iterate over array items until one fails
for (int i = 0; i < anArray.length; i++) {
T item = anArray[i];
if (!aPredicate.test(item)) {
array = anArray.clone();
length = i;
break;
}
}

// If one failed, iterate over remaining and copy over
if (array != anArray) {

for (int i = length + 1; i < anArray.length; i++) {
T item = anArray[i];
if (aPredicate.test(item)) {
array[length++] = item;
}
}

// Trim array
array = Arrays.copyOf(array, length);
}

// Return array
return array;
}
}

0 comments on commit 024f25a

Please sign in to comment.