PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

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

 September 05, 2022     java, string, trim     No comments   

Issue

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


Answered By - Avi
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing