Remove extension from file name with help of stream

Suule :

Currently I have some code which is returning me fileName with extension and to do that I am using java 8 stream api. But I would like to as well trim the String in the same Stream.

return Files.walk(Paths.get(qPath))
                      .filter(extension -> extension.toString().endsWith(".txt"))
                      .map(Path::getFileName)
                      .findFirst()
                      .map(Path::toString)
                      .get();

Any idea how to remove .txt from String in the stream?

Holger :

You are wasting resources by converting the path to a string multiple times. When the intended end result is a string anyway, you can map to a string right as the first step, so you don’t need to repeat it.

return Files.walk(Paths.get(qPath))
    .map(p -> p.getFileName().toString())
    .filter(name -> name.endsWith(".txt"))
    .map(name -> name.substring(0, name.length()-".txt".length()))
    .findFirst()
    .get();

Note that it doesn’t matter whether you place the last .map(…) step before the findFirst(), i.e. apply it to the Stream, or after it, applying it to the Optional. Due to the lazy nature of the Stream, it will still only applied to the first matching element here. But I prefer keeping the .endsWith(".txt") test and the subsequent .substring(0, name.length()-".txt".length()) as close together as possible, to make the relationship between these two steps more obvious.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91096&siteId=1