How can I convert an ArrayList String to String in Java

0 votes
I am using the toArray() method, but it is returning an object array rather than a string array
Apr 20, 2018 in Java by Parth
• 4,640 points
4,224 views

2 answers to this question.

0 votes
List<String> list = new ArrayList<String>();
String[] array = list.toArray(new String[0]);

For example:

List<String> alist = new ArrayList<String>();
alist.add("India");
alist.add("USA");
String[] stringArray = alist.toArray(new String[0]);

The toArray() method without passing any argument returns Object[].

So you have to pass an array as an argument.

answered Apr 20, 2018 by Daisy
• 8,140 points
0 votes

In Java 8 or later:

String listString = String.join(", ", list);

In case the list is not of type String, a joining collector can be used:

String listString = list.stream().map(Object::toString).collect(Collectors.joining(", "));
answered Aug 20, 2019 by Sirajul
• 59,190 points

Related Questions In Java

0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 59,190 points
3,243 views
+17 votes
25 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7, 2019 in Java by Suresh
• 720 points
261,794 views
0 votes
2 answers

How do I convert a String to an int in Java?

Use the lines of code mentioned below:- String ...READ MORE

answered Feb 9, 2022 in Java by Soham
• 9,730 points
4,107 views
0 votes
3 answers

How can I add new elements to an Array in Java

String[] source = new String[] { "a", ...READ MORE

answered Sep 19, 2018 in Java by Sushmita
• 6,920 points
14,859 views
+1 vote
1 answer

Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

answered Jun 26, 2018 in Java by scarlett
• 1,290 points
1,869 views
+1 vote
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,620 points
2,022 views