如何用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$", "")): Themapoperation transforms each string. The regex\\.ini$ensures we only match.iniwhen 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
相关产品推荐
相关产品推荐

