【问题标题】:Apply String modification to Array/List将字符串修改应用于数组/列表
【发布时间】:2018-10-22 07:33:27
【问题描述】:

鉴于具有文件扩展名的文件名ArrayList<String>,我怎样才能惯用地获得所有文件名无文件扩展名的相同数组。

有很多方法可以做到这一点,我可以轻松地创建一个新数组,但我想知道是否有一种干净的方法可以用单线做到这一点。

现在我正在这样做:

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

【问题讨论】:

    标签: java arrays string arraylist


    【解决方案1】:

    使用Streams:

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

    或:

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

    【讨论】:

    • 或者使用方法参考:.map(FilenameUtils::removeExtension)
    • 这就是我要找的 - 谢谢。我会等一天后再接受你的回答,看看有没有其他人也有什么要补充的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    相关资源
    最近更新 更多