简体   繁体   中英

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?

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(","));

MAYBE THIS WILL HELP YOU

ONE WAY:-

YOU CAN SAVE IT ON ANOTHER list splitStr2

List<String> ss = new ArrayList<String>();
for(String s:*splitStr*){ss.add(s.trim()); }

THIS ONE CHECK FOR NEW LIST ( WITHOUT_WHITESPACES )

for(String temp:ss){System.out.println(temp);}

*截屏*

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM