ArrayList to String with separated by Comma [duplicate] - java

This question already has answers here:
The simplest way to comma-delimit a list?
(30 answers)
Closed 6 years ago.
I have an ArrayList and I want to output completely as a String with separated by comma.
My code is
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (String s : list)
{
listString += s + ",";
}
System.out.println(listString);
But the output is one,two,three, and i want one,two,three without using replace method.
I am using JAVA

Using Java 8:
List<String> list = Arrays.asList(array);
String joinedString = String.join(",", list);

In Java 8+ you could use a StringJoiner (and you can use Arrays.asList(T...) to initialize your List). Something like,
List<String> list = Arrays.asList("one", "two", "three");
StringJoiner sj = new StringJoiner(",");
for (String s : list) {
sj.add(s);
}
System.out.println(sj.toString());
Output is (as requested)
one,two,three

import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (int i=0;i<list.size()-1;i++)
listString += list.get(i) + ",";
System.out.println(listString+list.get(list.size()-1));
}
}
Output:
one,two,three
http://ideone.com/PkAOOq

Just use String.substring. Here you go:
listString = listString.substring(0, listString.length() - 1);

You can use java.util.StringJoiner for this, instead of a List:
StringJoiner joiner = new StringJoiner(",");
joiner.add("one");
joiner.add("two"),
joiner.add("three");
String listString = joiner.toString();
If you are not using Java8, then consider using StringBuilder. Then your final string can be:
System.out.println(listString.substring(0, listString.length() - 1));

For a pre Java 8 solution, since the default toString() gives you [one, two, three].
String s = list.toString();
s = s.substring(1, s.length()-1);

try
list.toString().replace("[", "").replace("]", "");

Related

How to convert values to string? [duplicate]

I want the Java code for converting an array of strings into an string.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
From Java 8, the simplest way I think is:
String[] array = { "cat", "mouse" };
String delimiter = "";
String result = String.join(delimiter, array);
This way you can choose an arbitrary delimiter.
You could do this, given an array a of primitive type:
StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
result.append( a[i] );
//result.append( optional separator );
}
String mynewstring = result.toString();
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified
array. If the array contains other arrays as elements, the string
representation contains their contents and so on. This method is
designed for converting multidimensional arrays to strings
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
public class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
String newString = Arrays.toString(strArray);
newString = newString.substring(1, newString.length()-1);
System.out.println("New New String: " + newString);
}
}
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
String array[]={"one","two"};
String s="";
for(int i=0;i<array.length;i++)
{
s=s+array[i];
}
System.out.print(s);
Use Apache Commons' StringUtils library's join method.
String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character
//Deduplicate the comma character in the input string
String[] splits = input.split("\\s*,\\s*");
return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
If you know how much elements the array has, a simple way is doing this:
String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3];

How to get only the digits from list of string using java

I have list with combination of letters, digits and special characters. I need to extract the digits from string and store them in the same list.
I tried with below code
List<String> list = new LinkedList<String>();
list.add("132144, Test");
list.add("76876295, Test2");
//tried with replaceAll();
list.replaceAll(x->x.replace("[^0-9]",""));
//tried collection
Collections.replaceAll(list, "\\W+", "");
System.out.println(list);
Getting the output as [132144, Test,76876295, Test2], need output as [132144,76876295]
Stream the list, map each entry using a regular expression (\\D matches non-digits) to replace all non-digits with nothing. Collect that back into your original list (assuming you need to keep the new values only). Like,
list = list.stream().map(s -> s.replaceAll("\\D+", ""))
.collect(Collectors.toList());
System.out.println(list);
Outputs (as requested)
[132144, 768762952]
Your current input doesn't have such a case, but you might also filter out any empty String(s) after applying the regex.
list = list.stream().map(s -> s.replaceAll("\\D+", ""))
.filter(s -> !s.isEmpty()).collect(Collectors.toList());
You can do like this:
String line = "This order was32354 placed OK?8377jj";
String regex = "[^\\d]+";
String[] str = line.split(regex);
for(int i=0;i<str.length; i++) {
System.out.println(str[i]);
}
Output:
32354
8377
Hope this helps.
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
List<String> list1 = new LinkedList<String>();
list.add("132144, Test");
list.add("76876295, Test2");
for(String s:list)
list1.add(retriveDigits(s));
System.out.println(list1);
}
private static String retriveDigits(String str) {
return str.replaceAll("[^0-9]*", "");
}
}
Please find above class, I think that will help you.
you can use NumberUtils.isNumber() in stream like this:
list = list.stream()
.filter(NumberUtils::isNumber)
.collect(Collectors.toList());

Convert a List of Strings into a single String using ArrayUtils in java

I have below code
List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");
Need output as "one,two,three" in a single string using Array Utils. Need a single line solution.
Use join
String joined2 = String.join(",", test );
You can't do this with ArrayUtils. You can use Apache's StringUtils join function to get the result you want.
// result is "one,two,three"
StringUtils.join(test, ',');
If you don't want to use a library, you can create this function:
public static String joiner(List<String> list, String separator){
StringBuilder result = new StringBuilder();
for(String term : list) result.append(term + separator);
return result.deleteCharAt(result.length()-separator.length()).toString();
}
If you must use ArrayUtils then you could use List.toArray(T[]) (because ArrayUtils is for arrays) and a regular expression to remove { and } on one line like
List<String> test = new ArrayList<>(Arrays.asList("one", "two", "three"));
System.out.println(ArrayUtils.toString(test.toArray(new String[0]))
.replaceAll("[{|}]", ""));
Output is (as requested)
one,two,three
The String.join(CharSequence, Iterable<? extends CharSequence>) suggested by #Vishnu's answer offers a solution that eschews ArrayUtils (but is arguable better, assuming you can use it) with
String joined2 = String.join(",", test);
System.out.println(joined2);
which outputs the same.
List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");
Iterator it = test.iterator();
while(it.hasNext()){
String s=it.next();
StringBuilder sb = new StringBuilder();
sb.append(s);
}

Java: Convert List<Integer> to String

How can I convert List<Integer> to String? E.g. If my List<Integer> contains numbers 1 2 and 3 how can it be converted to String = "1,2,3"? Every help will be appreciated.
I think you may use simply List.toString() as below:
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
String listString = intList.toString();
System.out.println(listString); //<- this prints [1, 2, 3]
If you don't want [] in the string, simply use the substring e.g.:
listString = listString.substring(1, listString.length()-1);
System.out.println(listString); //<- this prints 1, 2, 3
Please note: List.toString() uses AbstractCollection#toString method, which converts the list into String as above
In vanilla Java 8 (streams) you can do
// Given numberList is a List<Integer> of 1,2,3...
String numberString = numberList.stream().map(String::valueOf)
.collect(Collectors.joining(","));
// numberString here is "1,2,3"
With Guava:
String s = Joiner.on(',').join(integerList);
One way would be:
Iterate over list, add each item to StringBuffer (or) StringBuilder and do toString() at end.
Example:
StringBuilder strbul = new StringBuilder();
Iterator<Integer> iter = list.iterator();
while(iter.hasNext())
{
strbul.append(iter.next());
if(iter.hasNext()){
strbul.append(",");
}
}
strbul.toString();
Just to add another (of many) options from a popular library (Apache Commons):
import org.apache.commons.lang3.StringUtils;
String joinedList = StringUtils.join(someList, ",");
See documentation: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join-java.lang.Iterable-java.lang.String-
An elegant option from others' comments (as of Java 8):
String joinedList = someList.stream().map(String::valueOf).collect(Collectors.joining(","));

How to convert a List<String> into a comma separated string without iterating List explicitly [duplicate]

This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 7 years ago.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Now i want an output from this list as 1,2,3,4 without explicitly iterating over it.
On Android use:
android.text.TextUtils.join(",", ids);
With Java 8:
String csv = String.join(",", ids);
With Java 7-, there is a dirty way (note: it works only if you don't insert strings which contain ", " in your list) - obviously, List#toString will perform a loop to create idList but it does not appear in your code:
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");
import com.google.common.base.Joiner;
Joiner.on(",").join(ids);
or you can use StringUtils:
public static String join(Object[] array,
char separator)
public static String join(Iterable<?> iterator,
char separator)
Joins the elements of the provided array/iterable into a single String containing the provided list of elements.
http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html
If you want to convert list into the CSV format .........
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
// CSV format
String csv = ids.toString().replace("[", "").replace("]", "")
.replace(", ", ",");
// CSV format surrounded by single quote
// Useful for SQL IN QUERY
String csvWithQuote = ids.toString().replace("[", "'").replace("]", "'")
.replace(", ", "','");
The quickest way is
StringUtils.join(ids, ",");
The following:
String joinedString = ids.toString()
will give you a comma delimited list. See docs for details.
You will need to do some post-processing to remove the square brackets, but nothing too tricky.
One Liner (pure Java)
list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");
Join / concat & Split functions on ArrayList:
To Join /concat all elements of arraylist with comma (",") to String.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String allIds = TextUtils.join(",", ids);
Log.i("Result", allIds);
To split all elements of String to arraylist with comma (",").
String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
Log.i("Result", element);
}
Done
I am having ArrayList of String, which I need to convert to comma separated list, without space. The ArrayList toString() method adds square brackets, comma and space. I tried the Regular Expression method as under.
List<String> myProductList = new ArrayList<String>();
myProductList.add("sanjay");
myProductList.add("sameer");
myProductList.add("anand");
Log.d("TEST1", myProductList.toString()); // "[sanjay, sameer, anand]"
String patternString = myProductList.toString().replaceAll("[\\s\\[\\]]", "");
Log.d("TEST", patternString); // "sanjay,sameer,anand"
Please comment for more better efficient logic.
( The code is for Android / Java )
Thankx.
You can use below code if object has attibutes under it.
String getCommonSeperatedString(List<ActionObject> actionObjects) {
StringBuffer sb = new StringBuffer();
for (ActionObject actionObject : actionObjects){
sb.append(actionObject.Id).append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
return sb.toString();
}
Java 8 solution if it's not a collection of strings:
{Any collection}.stream()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString()
If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));
If you can convert your ArrayList to a FastList, you can get rid of the adapter.
Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));
Note: I am a committer for Eclipse collections.
Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string
Output of this code will be: Veeru,Nikhil,Ashish,Paritosh
instead of output of list [Veeru,Nikhil,Ashish,Paritosh]
String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");
List_name = myNameList.toString().replace("[", "")
.replace("]", "").replace(", ", ",");

Categories