Skip to content

Instantly share code, notes, and snippets.

@enil
Created May 16, 2014 11:50
Show Gist options
  • Save enil/a3cf99a0044ffcbacce6 to your computer and use it in GitHub Desktop.
Save enil/a3cf99a0044ffcbacce6 to your computer and use it in GitHub Desktop.
public class ListTransformation {
private ListTransformation() { /* empty */ }
public static <T> List<T> collect(List<T> inputList, Predicate<T> predicate) {
List<T> newList = new ArrayList(inputList);
Iterator<T> iterator = newList.iterator();
while (iterator.hasNext()) {
try {
if (!predicate.check(iterator.next())) {
iterator.remove();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return newList;
}
public static <T> List<T> filter(List<T> inputList, Predicate<T> predicate) {
return collect(inputList, not(predicate));
}
public static <T> Predicate<T> not(final Predicate<T> predicate) {
return new Predicate<T>() {
public boolean check(T input) throws Exception {
return !predicate.check(input);
}
};
}
public static interface Predicate<T> {
public boolean check(T input) throws Exception;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment