Collection string to list string java

Initialize List of String in java

In this post, we will see how to initialize List of String in java.

Can you initialize List of String as below:

You can’t because List is an interface and it can not be instantiated with new List() .

You need to instantiate it with the class that implements the List interface.

Here are the common java Collections classes which implement List interface.

In most of the cases, you will initialize List with ArrayList as below.

If you are using java 7 or greater than you can use diamond operator with generics.

Initialize List of Strings with values

There are many ways to initialize list of Strings with values.

Arrays’s asList

You can use Arrays’s asList method to initialize list with values.

Stream.of (Java 8)

You can use java 8‘s Stream to initialize list of String with values.

List.of (Java 9)

Finally, java has introduced a of() method in List class to initialize list with values in java 9.

Using ArrayList’s add method

You can obviously initialize ArrayList with new operator and then use add method to add element to the list.

Using guava library

You can use guava library as well.

Here is the complete example.

That’s all about how to initialize List of String in java.

Was this post helpful?

Share this

Author

Convert UUID to String in Java

Table of ContentsIntroductionUUID class in JavaConvert UUID to String in Java Introduction In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look […]

Repeat String N times in Java

Table of ContentsIntroductionWhat is a String in Java?Repeat String N times in JavaSimple For Loop to Repeat String N Times in JavaUsing Recursion to Repeat String N Times in JavaString.format() method to Repeat String N Times in JavaUsing String.repeat() method in Java 11 to Repeat String N TimesRegular Expression – Regex to Repeat String N […]

How to Replace Space with Underscore in Java

Table of ContentsReplace space with underscore in java1. Using replace() method2. Using replaceAll() method Learn about how to replace space with underscore in java. Replace space with underscore in java 1. Using replace() method Use String’s replace() method to replace space with underscore in java. String’s replace() method returns a string replacing all the CharSequence […]

Читайте также:  Left pad string in java

How to Replace Comma with Space in Java

Table of ContentsReplace comma with space in java1. Using replace() method2. Using replaceAll() method Learn about how to replace comma with space in java. Replace comma with space in java 1. Using replace() method Use String’s replace() method to replace comma with space in java. Here is syntax of replace() method: [crayon-64c1ca83ba169965488273/] [crayon-64c1ca83ba16e499301151/] Output: 1 […]

Remove Parentheses From String in Java

Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusion Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text data at contiguous […]

Escape percent sign in java

Escape percent sign in String’s format method in java

Table of ContentsEscape Percent Sign in String’s Format Method in JavaEscape Percent Sign in printf() Method in Java In this post, we will see how to escape Percent sign in String’s format() method in java. Escape Percent Sign in String’s Format Method in Java String’s format() method uses percent sign(%) as prefix of format specifier. […]

Источник

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.

Источник

Split a String & Collect to List/Set/Collection :

1. Split a String using comma as delimiter & Collect to List :

  • Initially, we got a String with comma-separated values
  • Inside Arrays.stream(), split a String using comma as delimiter using String’s split() method
  • Then map a split-ted String using Stream.map() method to remove white-spaces if any
  • Collect split-ted String to List using Stream’s collect() method passing Collectors.toList() as argument
  • Finally, iterate & print List to console using List.forEach() method

SplitStringAndCollectToListUsingJava8Stream.java

package in.bench.resources.split.string; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class SplitStringAndCollectToListUsingJava8Stream < public static void main(String[] args) < // original string String fruits = "Grapes, Apple, Mango, Banana, Orange, Melons"; System.out.println("Original comma-separted String :- \n" + fruits); // split String based on comma ListfruitList = Arrays.stream(fruits.split("\\,")) // split on comma .map(str -> str.trim()) // remove white-spaces .collect(Collectors.toList()); // collect to List // print to console System.out.println("\nIterating & printing split-ted String from List :- "); fruitList.forEach(System.out::println); > >
Original comma-separted String :- Grapes, Apple, Mango, Banana, Orange, Melons Iterating & printing split-ted String from List :- Grapes Apple Mango Banana Orange Melons

2. Split a String using colon as delimiter & Collect to Set :

  • Initially, we got a String with colon-separated values
  • Inside Arrays.stream(), split a String using colon as delimiter using String’s split() method
  • Then map a split-ted String using Stream.map() method to remove white-spaces if any
  • Collect split-ted String to Set using Stream’s collect() method passing Collectors.toSet() as argument
  • Finally, iterate & print Set to console using Set.forEach() method

SplitStringAndCollectToSetUsingJava8Stream.java

package in.bench.resources.split.string; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; public class SplitStringAndCollectToSetUsingJava8Stream < public static void main(String[] args) < // original string String fruits = "Grapes:Apple:Mango:Banana:Orange:Melons"; System.out.println("Original colon-separted String :- \n" + fruits); // split String based on comma SetfruitList = Arrays.stream(fruits.split("\\:")) // split on colon .map(str -> str.trim()) // remove white-spaces .collect(Collectors.toSet()); // collect to Set // print to console System.out.println("\nIterating & printing split-ted String from Set :- "); fruitList.forEach(System.out::println); > >
Original colon-separted String :- Grapes:Apple:Mango:Banana:Orange:Melons Iterating & printing split-ted String from Set :- Apple Grapes Melons Mango Orange Banana

3. Split a String using Pipe as delimiter & Collect to any Collection :

  • Initially, we got a String with pipe-separated values
  • Inside Arrays.stream(), split a String using pipe as delimiter using String’s split() method
  • Then map a split-ted String using Stream.map() method to remove white-spaces if any
  • Collect split-ted String to any Collection classes using Stream’s collect() method passing Collectors.toCollection(TreeSet::new) as argument
  • Finally, iterate & print Collection to console using Set.forEach() method

SplitStringAndCollectToCollectionUsingJava8Stream.java

package in.bench.resources.split.string; import java.util.Arrays; import java.util.TreeSet; import java.util.stream.Collectors; public class SplitStringAndCollectToCollectionUsingJava8Stream < public static void main(String[] args) < // original string String fruits = "Grapes|Apple|Mango|Banana|Orange|Melons"; System.out.println("Original pipe-separted String :- \n" + fruits); // split String based on comma TreeSetfruitList = Arrays.stream(fruits.split("\\|")) // split on pipe .map(str -> str.trim()) // remove white-spaces .collect(Collectors.toCollection(TreeSet::new)); // collect to Collection // print to console System.out.println("\nIterating & printing split-ted String from Collection :- "); fruitList.forEach(System.out::println); > >
Original pipe-separted String :- Grapes|Apple|Mango|Banana|Orange|Melons Iterating & printing split-ted String from Collection :- Apple Banana Grapes Mango Melons Orange

References :

Happy Coding !!
Happy Learning !!

Источник

Java – How to Convert a String to ArrayList

Java - Convert String to ArrayList

In this java tutorial, you will learn how to convert a String to an ArrayList.

Input: 22,33,44,55,66,77
Delimiter: , (comma)
Output: ArrayList with 6 elements

Input: Welcome to BeginnersBook
Delimiter: ” ” (whitespace)
Output: ArrayList with 3 elements

The steps to convert string to ArrayList:

1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc.

2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays.asList() method. This method returns a list created based on the elements of the specified array.

Program to Convert String to ArrayList

In this java program, we are converting a comma separated string to arraylist in java. The input string consists of numbers and commas. We are splitting the string based on comma (,) as delimiter to get substrings. These substrings are assigned to ArrayList as elements.

import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class JavaExample < public static void main(String args[])< String num = "22,33,44,55,66,77"; String str[] = num.split(","); Listal = new ArrayList(); al = Arrays.asList(str); for(String s: al) < System.out.println(s); >> >

Note: In the above example, the delimiter is comma however we can split the string based on any delimiter. For example: if the string is “hello hi namaste bye” then we can split the string using whitespace as delimiter like this –

Here we have provided whitespace as delimiter String str[] = num.split(" ");

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Оцените статью