Skip to content

Commit

Permalink
Added lambda-friendly collection filtering utils in U.
Browse files Browse the repository at this point in the history
  • Loading branch information
nmihajlovski committed Oct 11, 2015
1 parent da3af88 commit 94de88c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions rapidoid-u/src/main/java/org/rapidoid/util/U.java
Expand Up @@ -56,6 +56,7 @@

import org.rapidoid.lambda.Dynamic;
import org.rapidoid.lambda.Mapper;
import org.rapidoid.lambda.Predicate;

/**
* @author Nikolche Mihajlovski
Expand Down Expand Up @@ -1031,4 +1032,32 @@ public static boolean exists(Callable<?> accessChain) {
}
}

public static <T> List<T> filter(List<T> items, Predicate<T> predicate) {
List<T> filtered = list();
addIf(items, filtered, predicate);
return filtered;
}

public static <T> Set<T> filter(Set<T> items, Predicate<T> predicate) {
Set<T> filtered = set();
addIf(items, filtered, predicate);
return filtered;
}

public static <T> void addIf(Collection<T> src, Collection<T> dest, Predicate<T> predicate) {
for (T item : src) {
boolean shouldAdd;

try {
shouldAdd = predicate.eval(item);
} catch (Exception e) {
throw rte(e);
}

if (shouldAdd) {
dest.add(item);
}
}
}

}

0 comments on commit 94de88c

Please sign in to comment.