You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java Lambda/Stream移除字符串数组的.ini后缀(禁用for循环)

Solution Using Java Stream API

Here's how you can modify your code to remove the .ini suffix using Stream and Lambda expressions, ditching the for loop entirely:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> applications = new ArrayList<>();
        String[] strings = { "1.ini", "2.ini", "3.ini", "test.ini.file" }; // Added edge case to show suffix-only matching
        applications.addAll(Arrays.asList(strings));
        
        // Process and print using Stream API
        applications.stream()
                    // Target only the .ini suffix at the end of the string
                    .map(s -> s.replaceAll("\\.ini$", ""))
                    // Print each transformed string
                    .forEach(System.out::println);
    }
}

Breakdown of the changes:

  • applications.stream(): Converts the list into a Stream, enabling functional-style processing of elements.
  • map(s -> s.replaceAll("\\.ini$", "")): The map operation transforms each string. The regex \\.ini$ ensures we only match .ini when it's at the end of the string (the $ anchors the match to the end). The double backslash escapes the dot, since in regex a single dot matches any character.
  • forEach(System.out::println): Replaces the traditional for loop by printing each modified string directly.

Output:

1
2
3
test.file

This approach keeps your code concise, follows your requirement of using Lambda/Stream, and avoids any explicit for loops.

内容的提问来源于stack exchange,提问作者Stéphane GRILLON

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:14:14