Question

I have a List of File object I want to filter according to some rules like typology (audio, video, photo) or capture date/time, or Exif informations (in case of photos). I can do it with some for cicles for example.

There's a smart way to do it? I read somewhere that the solution probably is to use Predicates from Google Guava, but I can't understand how it works. Any suggestion? Thanks

Was it helpful?

Solution

Using Guava Predicates you would do something along the lines of

import java.io.File;
import java.util.Collection;
import java.util.List;

import javax.annotation.Nullable;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.io.Files;

public class FileFiltering {

    public static void main(String[] args) {
        List<File> files = getFiles();
        Collection<File> audioFiles = Collections2.filter(files,
                new AudioPredicate());

        Collection<File> videoFiles = Collections2.filter(files,
                new VideoPredicate());
    }

    private static List<File> getFiles() {
        // TODO Auto-generated method stub
        return null;
    }
}

class AudioPredicate implements Predicate<File> {

    @Override
    public boolean apply(@Nullable File file) {
        return Files.getFileExtension(file.getName()).equalsIgnoreCase("mp3");
    }
}

class VideoPredicate implements Predicate<File> {

    @Override
    public boolean apply(@Nullable File file) {
        return Files.getFileExtension(file.getName()).equalsIgnoreCase("mkv");
    }
}

In the apply method(s) you will need to write code that will return true for the kind of file you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top