The simplest way to comma-delimit a list?
Java 8 and later
Using StringJoiner
class, and forEach
method :
StringJoiner joiner = new StringJoiner(",");
list.forEach(item -> joiner.add(item.toString());
return joiner.toString();
Using Stream
, and Collectors
:
return list.stream().
map(Object::toString).
collect(Collectors.joining(",")).toString();
Java 7 and earlier
See also #285523
String delim = "";
for (Item i : list) {
sb.append(delim).append(i);
delim = ",";
}
Best way to convert list to comma separated string in java
Since Java 8:
String.join(",", slist);
From Apache Commons library:
import org.apache.commons.lang3.StringUtils
Use:
StringUtils.join(slist, ',');
Another similar question and answer here
Convert a list of string into a comma separated string without duplications
The best to avoid duplicates is to use a Set
TreeSet
for alphabetical orderLinkedHashSet
to keep insertion order (initial order)
StringBuilder result = new StringBuilder();
String delimiter= "";
for (String i : new LinkedHashSet<String>(list)) {
result.append(delimiter).append(i);
delimiter = ",";
}
return result.toString();
But you can just do String.join(',', new LinkedHashSet<String>(list))
Back to List
List<String> inputList = (unique) ? new ArrayList<>(new HashSet<>(list)) : list;
Case-insensitive
Set<String> check = new HashSet<String>();
StringBuilder result = new StringBuilder();
String delimiter= "";
for (String i : list) {
if(!check.contains(i.toLowerCase())){
result.append(delimiter).append(i);
delimiter = ",";
check.add(i.toLowerCase());
}
}
return result.toString();
Convert a list of integers into a comma-separated string
Yes. However, there is no Collectors.joining
for a Stream<Integer>
; you need a Stream<String>
so you should map
before collecting. Something like,
System.out.println(i.stream().map(String::valueOf)
.collect(Collectors.joining(",")));
Which outputs
1,2,3,4,5
Also, you could generate Stream<Integer>
in a number of ways.
System.out.println(
IntStream.range(1, 6).boxed().map(String::valueOf)
.collect(Collectors.joining(","))
);
How would you make a comma-separated string from a list of strings?
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
my_string = ','.join(map(str, my_list))
Creating a comma separated list from IListstring or IEnumerablestring
.NET 4+
IList<string> strings = new List<string>{"1","2","testing"};
string joined = string.Join(",", strings);
Detail & Pre .Net 4.0 Solutions
IEnumerable<string>
can be converted into a string array very easily with LINQ (.NET 3.5):
IEnumerable<string> strings = ...;
string[] array = strings.ToArray();
It's easy enough to write the equivalent helper method if you need to:
public static T[] ToArray(IEnumerable<T> source)
{
return new List<T>(source).ToArray();
}
Then call it like this:
IEnumerable<string> strings = ...;
string[] array = Helpers.ToArray(strings);
You can then call string.Join
. Of course, you don't have to use a helper method:
// C# 3 and .NET 3.5 way:
string joined = string.Join(",", strings.ToArray());
// C# 2 and .NET 2.0 way:
string joined = string.Join(",", new List<string>(strings).ToArray());
The latter is a bit of a mouthful though :)
This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) this one.
As of .NET 4.0, there are more overloads available in string.Join
, so you can actually just write:
string joined = string.Join(",", strings);
Much simpler :)
Easiest way to convert list to a comma separated string by a Specific Property?
This is very easy , Isn't it ?
string sCategories = string.Join(",", categories.Select(x => x.Name));
Easy way to turn JavaScript array into comma-separated list?
The Array.prototype.join() method:
var arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));
Related Topics
Serialization - Readobject Writeobject Overrides
How to Get a Reference Address
How to Convert Current Date into String in Java
Prevent SQL Injection Attacks in a Java Program
Running Multiple Launch Configurations at Once
Create a New Line in Java's Filewriter
How Does Java's System.Exit() Work with Try/Catch/Finally Blocks
Hibernate - @Elementcollection - Strange Delete/Insert Behavior
How to Parse Datetime-String with Am/Pm Marker
Java Date - Insert into Database
Is a Volatile Int in Java Thread-Safe
Convert Base64 String to Image
Arraylist Initial Capacity and Indexoutofboundsexception