I have a large collection with many entries: Set<File> allFiles.
Is it practical to iterate through this Set using the following algorithm? Are there better ways to do it?
Set<File> allFiles = // ...100,000+ entries
Set<File> filteredList = new LinkedHashSet<File>();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Extensions accepted", "a", "b", "c");
for (File file : allFiles) {
if (filter.accept(file)) {
filteredList.add(file);
}
}
In case anyone is asking, the allFiles Set is pre-populated elsewhere, and not necessarily gleaned using the File.listFiles() method.
If by practical you mean writeable in 5 lines in java yes it is. There is no cleaner alternatives when you want to filter a list (as opposed to languages with functional constructs like Scala and its filter method).
I personaly do not see how you could do it better, if your use case is really to filter out files with bad extensions I would do the same in Java.
If you are worried to use interfaces and classes from
javax.swingyou should not, both these classes depend only onjava.ioorjava.util.Locale(for setting file name to lowercase according to english locale), so they are as clean as theFilenameFilterfromjava.io. If your deal is really to filter according to case insensitive extension you should definitely go this way, the only alternative my eclipse sees iscom.google.gwt.thirdparty.guava.common.io.PatternFilenameFilterimplementingjava.io.FilenameFilter, but then you have a new dependency and you write a Regex pattern which is far less readable and maintainable than your extensions. So I would stay withFileNameExtensionFilterif this is really your use case.