- Convert a comma-separated string to a list in Java
- You might also like.
- String Operations with Java Streams
- 1. Overview
- 2. Joining Strings With the Stream API
- 3. Splitting Strings With Stream API
- 4. String Array to Map With Stream API
- 5. Testing
- 6. Conclusion
- Java split string to list string
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Convert a comma-separated string to a list in Java
There are many ways to convert a comma-separated string into a list in Java. In this article, we’ll look at three different methods to convert a string with a separator to a list.
The String class in Java provides split() method to split a string into an array of strings. You can use this method to turn the comma-separated list into an array:
String fruits = "🍇,🍓,🍑,🥭,🍍,🥑"; String [] fruitsArray = fruits.split(",");
ListString> fruitsList = Arrays.asList(fruitsArray);
String fruits = "🍇,🍓,🍑,🥭,🍍,🥑"; ListString> fruitsList = Arrays.asList(fruits.split(",")); System.out.println(fruitsList); // [🍇, 🍓, 🍑, 🥭, 🍍, 🥑]
If the comma-separated string contains white spaces, you can pass a regular expression to split() to remove them:
String fruits = "🍇, 🍓, 🍑, 🥭, 🍍, 🥑"; ListString> fruitsList = Arrays.asList(fruits.split("\\s*,\\s*"));
String fruits = "🍇, 🍓, 🍑, 🥭, 🍍, 🥑"; ListString> fruitsList = Stream.of(fruits.split("\\s*,\\s*")) .collect(Collectors.toList()); System.out.println(fruitsList); // [🍇, 🍓, 🍑, 🥭, 🍍, 🥑]
In the above example, we first used the split() method to convert our fruits string into an array of strings. Then, we used the Stream class to convert the array into a list of strings. An additional benefit of using Java Stream API is that you can perform other operations on the elements of the array before converting them into a list. Look at the following example that converts a string of numbers into a list of integers using a stream:
String numbers = "23, 45, 2, 7, 99, 6"; ListInteger> list = Stream.of(numbers.split(",")) .map(String::trim) .map(Integer::parseInt) .collect(Collectors.toList()); System.out.println(list); // [23, 45, 2, 7, 99, 6]
The first part of the example is the same, convert a comma-separated string of numbers into an array. Then, it trims the leading and trailing spaces from each string on the stream using the map(String::trim) method. Next, the map(Integer::parseInt) method is called on our stream to convert every string to an Integer . Finally, it calls the collect(Collectors.toList()) method on the stream to transform it into an integer list.
Apache Commons Lang is an open-source library that provides many utility classes to manipulate core Java classes. One such utility class is the StringUtils that offers utility methods for string operations. To add Commons Lang to your Maven project, add the following dependency to the pom.xml file:
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.12.0version> dependency>
implementation 'org.apache.commons:commons-lang3:12.0'
Now you can use the StringUtils.splitPreserveAllTokens() method to convert the string into an array of strings:
String[] fruitsArray = StringUtils.splitPreserveAllTokens(fruits, ",");
ListString> fruitsList = Arrays.asList(fruitsArray);
Both split() and splitPreserveAllTokens() methods split the string into an array of strings using a delimiter. However, the splitPreserveAllTokens() method preserves all tokens, including the empty strings created by adjoining separators, while the split() method ignores empty strings. Read Next: Convert a list to a comma-separated string in Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
String Operations with Java Streams
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
Java 8 has introduced a new Stream API that lets us process data in a declarative manner.
In this quick article, we would learn how to use the Stream API to split a comma-separated String into a list of Strings and how to join a String array into a comma-separated String.
We’ll also look at how to convert a string array to map using Stream API.
Nearly all of the time we face situations, where we need to iterate some Java Collections and filter the Collection based on some filtering logic. In a traditional approach for this type of situation, we would use lots of loops and if-else operations to get the desired result.
If you want to read more about the Stream API, check this article.
2. Joining Strings With the Stream API
Let’s use the Stream API to create a function which would join a String array into a comma-separated String:
public static String join(String[] arrayOfString)< return Arrays.asList(arrayOfString) .stream() //.map(. ) .collect(Collectors.joining(",")); >
- The stream() function converts any Collection into a stream of data
- map() function is used to process the data
- There is also another function, named filter(), where we can include filtering criteria
There can be scenarios, where we may want to join a String with some fixed prefix and postfix. With the Stream API we can do that in the following way:
public static String joinWithPrefixPostfix(String[] arrayOfString)< return Arrays.asList(arrayOfString) .stream() //.map(. ) .collect(Collectors.joining(",","[","]")); >
As we can see in the Collectors.joining() method, we are declaring our prefix as ‘[‘ and postfix as ‘]’; hence the generated String will be created with declared […..] format.
3. Splitting Strings With Stream API
Now, let’s create a function, which would split a comma separated String into a list of String using Stream API:
public static List split(String str) < return Stream.of(str.split(",")) .map (elem ->new String(elem)) .collect(Collectors.toList()); >
It’s also possible to directly convert a String to a Character list using the Stream API:
public static List splitToListOfChar(String str) < return str.chars() .mapToObj(item ->(char) item) .collect(Collectors.toList()); >
One interesting fact to note here is that the chars() method converts the String into a stream of Integer where each Integer value denotes the ASCII value of each and every Char sequence. That’s why we need to explicitly typecast the mapper object in the mapToObj() method.
4. String Array to Map With Stream API
We can also convert a String array to map using split and Collectors.toMap, provided each item in the array contains a key-value entity concatenated by a separator:
public static Map arrayToMap(String[] arrayOfString) < return Arrays.asList(arrayOfString) .stream() .map(str ->str.split(":")) .collect(toMap(str -> str[0], str -> str[1])); >
Here, “:” is the key-value separator for all the elements in String array.
Please remember that in order to avoid compilation error, we need to ensure that code is compiled using Java 1.8. To do this, we need to add the following plugin in the pom.xml:
org.apache.maven.plugins maven-compiler-plugin 3.3 1.8
5. Testing
Since we are done creating the functions, let’s create test cases to verify the outcome.
First, let’s test our simple joining method:
@Test public void givenArray_transformedToStream_convertToString() < String[] programmingLanguages = ; String expectation = "java,python,nodejs,ruby"; String result = JoinerSplitter.join(programmingLanguages); assertEquals(result, expectation); >
Next, let’s create another one to test our simple splitting functionality:
@Test public void givenString_transformedToStream_convertToList() < String programmingLanguages = "java,python,nodejs,ruby"; Listexpectation = new ArrayList<>(); expectation.add("java"); expectation.add("python"); expectation.add("nodejs"); expectation.add("ruby"); List result = JoinerSplitter.split(programmingLanguages); assertEquals(result, expectation); >
Finally, let’s test our String array to map functionality:
@Test public void givenStringArray_transformedToStream_convertToMap() < String[] programming_languages = new String[] ; Map expectation=new HashMap<>(); expectation.put("language", "java"); expectation.put("os", "linux"); expectation.put("editor", "emacs"); Map result = JoinerSplitter.arrayToMap(programming_languages); assertEquals(result, expectation); >
In the same way, we need to create the rest of the test cases.
6. Conclusion
Stream API provides us with sophisticated data processing techniques. This new way of writing code is very efficient in terms of heap memory management in a multi-threaded environment.
Like always, the full source code is available over on Github.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Java split string to list string
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter