Details
-
New Feature
-
Status: Closed
-
Trivial
-
Resolution: Fixed
-
None
-
None
Description
I recently needed a way to use a Predicate to select things from a list, but I also wanted to know which ones failed the predicate test.
I wanted the following, but with one iteration instead of two:
List originalList = (...) Predicate p = (...) Collection selected = CollectionUtils.select(originalList, p); Collection rejected = CollectionUtils.selectRejected(originalList, p); // handle the selected cases (save them or whatnot) // now throw an error message or handle the rejected cases
This is what I came up with based on the CollectionUtils.select(...) method:
public static <O, R extends Collection<? super O>> void bisect( final Iterable<? extends O> inputCollection, final Predicate<? super O> predicate, final R selectedCollection, final R rejectedCollection) { if (inputCollection != null && predicate != null) { for (final O item : inputCollection) { if (predicate.evaluate(item)) { selectedCollection.add(item); }else{ rejectedCollection.add(item); } } } } public static void main(String[] args){ // this will test the bisection code List<String> original = Arrays.asList( "testString1", "testString2", "testString3", "String1", "String2", "String3", "testString4", "String4", "testString5" ); List<String> selected = new ArrayList<String>(); List<String> rejected = new ArrayList<String>(); Predicate<String> beginsWithTestPredicate = new Predicate<String>() { public boolean evaluate(String object) { return object.startsWith("test"); } }; bisect(original, beginsWithTestPredicate, selected, rejected); System.out.println("Size of selected (should be 5):" + selected.size()); System.out.println("Size of rejected (should be 4):" + rejected.size()); }
This will of course throw a NullPointerException if either output collection is null. This seems appropriate since we need to return two outputs anyway.
Not sure if bisect is the best name, but this method will split the original into two pieces. https://www.google.com/#q=define+bisect