Skip to content

Commit 3ee04db

Browse files
authored
Add object-oriented methods for filter and reject.
1 parent 6232744 commit 3ee04db

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/main/java/com/github/underscore/$.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,16 @@ public static <E> List<E> filter(final List<E> list, final Predicate<E> pred) {
320320
return filtered;
321321
}
322322

323+
public List<T> filter(final Predicate<T> pred) {
324+
final List<T> filtered = newArrayList();
325+
for (final T element : value()) {
326+
if (pred.apply(element)) {
327+
filtered.add(element);
328+
}
329+
}
330+
return filtered;
331+
}
332+
323333
public static <E> List<E> filterIndexed(final List<E> list, final PredicateIndexed<E> pred) {
324334
final List<E> filtered = newArrayList();
325335
int index = 0;
@@ -359,6 +369,15 @@ public Boolean apply(E input) {
359369
});
360370
}
361371

372+
public List<T> reject(final Predicate<T> pred) {
373+
return filter(new Predicate<T>() {
374+
@Override
375+
public Boolean apply(T input) {
376+
return !pred.apply(input);
377+
}
378+
});
379+
}
380+
362381
public static <E> List<E> rejectIndexed(final List<E> list, final PredicateIndexed<E> pred) {
363382
return filterIndexed(list, new PredicateIndexed<E>() {
364383
@Override

src/test/java/com/github/underscore/CollectionsTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,13 @@ public Boolean apply(Integer item) {
509509
}
510510
});
511511
assertEquals("[2, 4, 6]", result.toString());
512+
final List<Integer> resultObject = new $<Integer>(asList(1, 2, 3, 4, 5, 6))
513+
.filter(new Predicate<Integer>() {
514+
public Boolean apply(Integer item) {
515+
return item % 2 == 0;
516+
}
517+
});
518+
assertEquals("[2, 4, 6]", resultObject.toString());
512519
}
513520

514521
/*
@@ -571,6 +578,13 @@ public Boolean apply(Integer item) {
571578
}
572579
});
573580
assertEquals("[1, 3, 5]", result.toString());
581+
final List<Integer> resultObject = new $<Integer>(asList(1, 2, 3, 4, 5, 6))
582+
.reject(new Predicate<Integer>() {
583+
public Boolean apply(Integer item) {
584+
return item % 2 == 0;
585+
}
586+
});
587+
assertEquals("[1, 3, 5]", resultObject.toString());
574588
final Set<Integer> resultSet = $.reject(new LinkedHashSet(asList(1, 2, 3, 4, 5, 6)),
575589
new Predicate<Integer>() {
576590
public Boolean apply(Integer item) {

0 commit comments

Comments
 (0)