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?
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());
Just do a replacing of all whitespaces before doing iterations:
String Str = "E_1000, E_1005,E_1010 , E_1015,E_1020,E_1025".replace(" ", "");
List<String> splitStr = Arrays.asList(Str.split(","));
Not sure whether single elements may contain spaces. If not, simply remove all spaces:
List<String> splitStr = Arrays.asList(Str.replace(" ", "").split(","));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.