Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Filter an Element from a List

Tags:

java

guava

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.

like image 654
McGlone Avatar asked Nov 21 '25 01:11

McGlone


1 Answers

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()));
}
like image 136
ColinD Avatar answered Nov 23 '25 14:11

ColinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!