How to Filter an Element from a List

guava, java

Solution

You could compose a regex matching predicate with the `toString()` function:

public Iterable<File> getSurveyFiles() {
  return Iterables.filter(files, Predicates.compose(
      Predicates.not(Predicates.containsPattern("\\.asp$")),
      Functions.toStringFunction()));
}

Problem

I'm trying to implement a fairly simple method in which I want to filter a list. This is a list of File objects and there should be exactly one file that ends with .asp - I want that one excluded from the list. Keep in mind that I don't actually want to remove this file from the list, I just want to be able to ignore it for a specific iteration of that list. My original (brute force) implementation looked like this: ``` public List<File> getSurveyFiles() throws Exception { List<File> surveyFiles = new ArrayList<File>(files.size() - 1); for ( File f : files ) { if ( !f.getName().endsWith(".asp") ) { surveyFiles.add(f); } } return surveyFiles; } ``` It works, but it feels very wasteful in the fact that I am creating a second list and doing a lot of copying from one list to another. Another option I've toyed with is to use guava-libraries (http://code.google.com/p/guava-libraries/) and utilizing their filter function, like this: ``` public class SurveyFileControllerPredicate implements Predicate<File> { @Override public boolean apply(File file) { return file.getName().endsWith(".asp"); } } ... public Iterable<File> getSurveyFiles() throws Exception { return Iterables.filter( files, Predicates.not(new SurveyFileControllerPredicate()) ); } ``` The implementation of filter removes the .asp file at iteration time, rather than ahead of time, so this code has the benefit of not making a second List, but I feel that it makes my code more complex. Are there other, simpler, implementations that I'm not considering? In the whole scheme of things, which implementation I choose probably doesn't matter. I'm just curious how other developers would tackle this and what option they would choose. Thanks.

Original source