How to convert an ArrayList
to a String
in Java?
The toString
method returns it as [a,b,c]
string - I wa
Many solutions available. You can iterate over the chars and append to a StringBuilder, then when finished appending, call .toString on the StringBuilder.
Or use something like commons-lang StringUtils.join from the apache commons-lang project.
a tiny complement to @waggledans 's answer
a) List of Character objects to String :
String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());
which e->e.toString()
can be replaced by Object::toString
String str = chars.stream().map(Object::toString).collect(Collectors.joining());
Here a possible one-line solution using Java8 streams.
a) List of Character objects to String :
String str = chars.stream().map(e->e.toString()).reduce((acc, e) -> acc + e).get();
b) array of chars (char[] chars)
String str = Stream.of(chars).map(e->new String(e)).reduce((acc, e) -> acc + e).get();
UPDATE (following comment below):
a) List of Character objects to String :
String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());
b) array of chars (char[] chars)
String str = Stream.of(chars).map(e->new String(e)).collect(Collectors.joining());
How about this, Building the list
List<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
Actual code to get String from List of Character:
String word= new String();
for(char c:charsList){
word= word+ c;
}
System.out.println(word);
Still learning if there is a misake point out.
Using join
of a Joiner
class:
// create character list and initialize
List<Character> arr = Arrays.asList('a', 'b', 'c');
String str = Joiner.on("").join(arr);
System.out.println(str);
Use toString
then remove , and spaces
import com.google.common.base.Joiner;
....
<Character> arr = Arrays.asList('h', 'e', 'l', 'l', 'o');
// remove [] and spaces
String str = arr.toString()
.substring(1, 3 * str.size() - 1) //3 bcs of commas ,
.replaceAll(", ", "");
System.out.println(str);
Or by using streams:
import java.util.stream.Collectors;
...
// using collect and joining() method
String str = arr.stream().map(String::valueOf).collect(Collectors.joining());