2

Given an ArrayList<String> of filenames with file extension, how can I idiomatically get that same array with all the filenames sans file extension.

There's a lot of ways to do this and I could easily just create a new array but I'm wondering if there's a nice clean way to do this with a one-liner.

For now I am doing like so:

List<String> namesWithExt = ...
List<String> namesWithoutExt = new ArrayList<>();
namesWithExt.forEach(name -> namesWithoutExt.add(FilenameUtils.removeExtension(name)));
String[] namesWithoutExt = namesWithExt.toArray(String[]::new);

1 Answer 1

4

Use Streams:

String[] namesWithoutExt = 
    namesWithExt.stream()
                .map(name -> FilenameUtils.removeExtension(name))
                .toArray(String[]::new);

or:

String[] namesWithoutExt = 
    namesWithExt.stream()
                .map(FilenameUtils::removeExtension)
                .toArray(String[]::new);
Sign up to request clarification or add additional context in comments.

2 Comments

Or using a method reference: .map(FilenameUtils::removeExtension)
This is what I'm looking for - thanks. I'm gonna wait a day before I accept your answer to see if anyone else has something to add as well.

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.