0

I want to create a FileNameFilter using a lambda function.

My main problem is that I want to introduce a loop inside the function. I tried using filters but I am unable to create filters based on external list.

Following is my code:

    File targetDir = new File(path);
    FilenameFilter deleteFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            for(String tag: pageTagsList){
                if(name.equals(tag))
                    return true;
            }
            return false;
        }
    };
    File[] foundFiles = targetDir.listFiles(deleteFilter);

What I want to do is something like this:

File[] foundFiles = targetDir.listFiles(
            (dir,name)->pageTagsList.stream()
            .filter(//code to filter here)
            .orElse(false)
            );

Is there a correct way to do this?

1
  • Maybe this is a contrived example and the point is to know how to iterate within a lambda body in general, but if not, the best solution would be to use a pageTagsSet of type Set<String>. Looking up in a HashSet is way faster than iterating over a list. So (dir,name)->pageTagsList.contains(name) would do it Commented Oct 20, 2016 at 23:07

4 Answers 4

6

You can have a lambda be any code block (though any variables referenced from inside of it must be final). For your desired outcome you can do something like the following:

File[] foundFiles = targetDir.listFiles((dir, name) -> pageTagsList.stream().anyMatch(name::equals));
Sign up to request clarification or add additional context in comments.

Comments

2

A lambda can contain a block of code. The syntax is like this:

(params) -> {
    // Some code.

    for (Element elem : elements) {
        // Some code using elem.
    }

    return returnValue;
}

Comments

1
List<String> tags = pageTagList
                   .stream()
                   .filter(t -> t.equals(name)).collect(Collectors.toList());

If you need explanation of anything above, just ask in comment. I find this code self explaining.

Comments

1
@Override
public boolean accept(File dir, String name) {    
    return pageTagsList.stream()
        .filter(name::equals)
        .findAny()
        .isPresent()
}
  • This is just showcase of returning true/false, answer from Aaron Davis is most elegant

1 Comment

Actually, the most elegant solution is pageTagsList.contains(name). Since Java 2…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.