3

Prior to Java 8, this method would be used to create a list of hidden files:

    File[] hiddenFiles = new File("./directory/").listFiles(new FileFilter() {
        public boolean accept(File file) {
            return file.isHidden();
        }
    });

In Java 8, this can be shortened to:

File[] hiddenFiles = new File("./directory/").listFiles(File::isHidden);

Returning non-hidden files in the original code was a trivial change: return file.!isHidden(); as a substitute for return file.isHidden();. I cannot recreate this functionality within a single line.

There is no isNotHidden function within the File class. Without creating one (or without deferring to the original, more verbose code), is there a way to recreate it using the new single-line style?

Michael
  • 41,989
  • 11
  • 82
  • 128
MK_Codes
  • 33
  • 1
  • 5
  • 4
    You can use `listFiles(f -> !f.isHidden())`. You can't negate a method reference. – daniu Aug 08 '18 at 15:11
  • 3
    **"Returning non-hidden files in the original code was a trivial change: `return file.!isHidden();`"** Not that trivial apparently, because that's not valid syntax. ;) – Michael Aug 08 '18 at 15:26
  • 2
    @daniu you can do via `Predicate.not(File::isHidden)` in java-11 – Eugene Aug 08 '18 at 15:44
  • 1
    Here's the original bug: https://bugs.openjdk.java.net/browse/JDK-8050818 – Ravindra Ranwala Aug 08 '18 at 16:32
  • 1
    @Michael: Hah, oops. Maybe I should start copying code in from my IDE rather than trying to remember it! It does look like that other answer hits mine though, thanks for that. – MK_Codes Aug 09 '18 at 07:29
  • @Eugene for completeness sake: you can also negate the predicate itself in Java 8 if you assign it first: `Predicate notHidden = File::isHidden; notHidden = notHidden.negate();` – daniu Aug 13 '18 at 05:52
  • @daniu or even `((Predicate)File::isHidden).negate()`, but neither is as nice as the java-11 one – Eugene Aug 13 '18 at 07:56

2 Answers2

3

How about this,

File[] hiddenFiles = new File("c:/data").listFiles(f -> !f.isHidden());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
3

Coming in java-11 Predicate.not, until then you can't via a method reference

Predicate.not(File::isHidden)
Eugene
  • 117,005
  • 15
  • 201
  • 306