Using JShell of java 13.0.1 on Debian Stretch:
import static java.nio.file.Files.*;
var hm=Path.of(System.getProperty("user.home"));
void p(String s) {System.out.println(s);}
list(hm).sorted((a,b)->a.compareTo(b)).forEach(x -> p(x.toString().substring(hm.toString().length()+1)));
list(hm).sorted().forEach(x -> p(x.toString().substring(hm.toString().length()+1)));
"a".compareToIgnoreCase("A");
This all works (it lists the files in the home folder two times, and returns 0).
But when I enter:
list(hm).sorted((a,b)->a.compareToIgnoreCase(b)).forEach(x -> p(x.toString().substring(hm.toString().length()+1)));
It leads to an error:
Cannot find symbol, symbol: method compareToIgnoreCase.
Any idea what make compareToIgnoreCase to fail?
hm
is a Path
, thus list(hm)
returns a Stream<Path>
. There is no method compareToIgnoreCases(...)
in class Path
. If one wants to use compareToIgnoreCase
from String
, one needs to transform the Path
to String
first, e.g. by calling toString()
:
list(hm)
.sorted((a,b) -> a.toString().compareToIgnoreCase(b.toString()))
.forEach(x -> p(x.toString().substring(hm.toString().length() + 1)));
Looking at what is done in the stream-chain, mapping the entries to String
before further execution seems sensible:
list(hm)
.map(Path::toString) // convert Stream<Path> to Stream<String>
.sorted(String::compareToIgnoreCase)
.map(x -> x.substring(hm.toString().length() + 1))
.forEach(this::p);
(The code above assumes that p
is an instance method of the this
-object)