Tal Angel
Tal Angel

Reputation: 1780

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?

Upvotes: 4

Views: 9126

Answers (4)

Frank Tirkey
Frank Tirkey

Reputation: 39

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);}

*screenshot*

Upvotes: 1

Avi
Avi

Reputation: 2641

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

Upvotes: 20

Robert Kock
Robert Kock

Reputation: 6028

Not sure whether single elements may contain spaces. If not, simply remove all spaces:

List<String> splitStr = Arrays.asList(Str.replace(" ", "").split(","));

Upvotes: 0

mrkernelpanic
mrkernelpanic

Reputation: 4461

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

Upvotes: 0

Related Questions