Search code examples
javastringtrim

How to split string into list and trim in one line Java


Please look at my code

 String Str = "E_1000, E_1005,E_1010 , E_1015,E_1020,E_1025";
                List<String> splitStr = Arrays.asList(Str.split(","));

My list (splitStr) has strings with white spaces.

Is there a way to split the string and trim all the elements in one line of code?


Solution

  • Yes, simply do:

    String str = "E_1000, E_1005,E_1010 , E_1015,E_1020,E_1025";
    List<String> splitStr = Arrays.stream(str.split(","))
        .map(String::trim)
        .collect(Collectors.toList());
    

    Explanation:
    First, we split on ,:

                                          str.split(",")
    

    Then, we turn it into a Stream of (untrimmed) Strings:

                            Arrays.stream(str.split(","))
    

    Next, we trim all the Strings in the Stream:

                            Arrays.stream(str.split(","))
        .map(String::trim)
    

    Finally, we collect all the trimmed Strings into a List:

                            Arrays.stream(str.split(","))
        .map(String::trim)
        .collect(Collectors.toList());