Monday, August 11, 2014

Using Labmda Expression in File Filtering

Java 8 makes it so easy to write the anonymous functions which can be understood using the following file filtering example:

Before Java 8:
    public static List fileList(String directory) {
        List fileNames = new ArrayList<>();
        
        DirectoryStream.Filter filter = 
              new DirectoryStream.Filter() {
         @Override
         public boolean accept(Path file) throws IOException {
           return (Files.size(file) > 8192L);
         }
        };
        
        try (DirectoryStream directoryStream = 
          Files.newDirectoryStream(Paths.get(directory), filter)) {
            for (Path path : directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException ex) {}
        return fileNames;
    }
With Java 8:
    public static List fileListWithLambda(String directory) {
        List fileNames = new ArrayList<>();
        
        DirectoryStream.Filter filter = 
          (Path file) -> (Files.size(file) > 8192L);
        
        try (DirectoryStream directoryStream = 
          Files.newDirectoryStream(Paths.get(directory), filter)) {
            for (Path path : directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException ex) {}
        return fileNames;
    }

No comments: