使用Java 8 Streams修改嵌套列表中的字符串
Optimizing Nested List Trimming with Java 8 Streams
Nice work getting a working solution! You're already using streams for the inner lists, but we can take this a step further by eliminating the explicit for loop and handling the entire nested structure with a single stream pipeline. This makes the code more declarative, concise, and fully leverages Java 8's stream capabilities.
Here's the optimized version:
import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { ArrayList<List<String>> listOfListsOfStrings = new ArrayList<>(); listOfListsOfStrings.add(Arrays.asList("abc ", "bd ", " asd ", "s")); listOfListsOfStrings.add(Arrays.asList("123 ", "45 ", " 753 ", "111")); listOfListsOfStrings.add(Arrays.asList("sdfg2 ", "b23d ", " as123d ", "1s1")); // Stream-based transformation (no explicit for-loop) List<List<String>> trimmedListOfLists = listOfListsOfStrings.stream() .map(innerList -> innerList.stream() .map(String::trim) .collect(toList())) .collect(toList()); // Optional: If you specifically need an ArrayList as the outer collection ArrayList<List<String>> trimmedArrayList = listOfListsOfStrings.stream() .map(innerList -> innerList.stream() .map(String::trim) .collect(toList())) .collect(Collectors.toCollection(ArrayList::new)); // Verify the output listOfListsOfStrings.forEach(list -> list.forEach(System.out::println)); System.out.println("------------------"); trimmedListOfLists.forEach(list -> list.forEach(System.out::println)); } }
Key improvements over your original code:
- No manual loop or mutable container: We replace the
newListOfListsinitialization andforloop with a stream pipeline that directly transforms the entire nested structure in one go. - Declarative style: The code focuses on what we want to do (trim every string in every inner list) rather than how to do it (iterating, adding to a new list).
- Flexible collection: Use
toList()for a general-purpose list, ortoCollection(ArrayList::new)if you explicitly need anArrayListfor downstream processes.
Why this works:
- We start with a stream of the outer lists (
listOfListsOfStrings.stream()). - For each inner list, we apply another stream to trim every string (
innerList.stream().map(String::trim).collect(toList())). - Finally, we collect all the transformed inner lists into a new outer list.
This approach keeps your code clean, reduces boilerplate, and fully embraces the functional programming features introduced in Java 8.
内容的提问来源于stack exchange,提问作者user2871219
相关产品推荐
相关产品推荐

