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 parth295
• 4,600 points
148 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,050 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 5 days ago by Sirajul
• 19,670 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 5 days ago in Java by Sirajul
• 19,670 points
113 views
+14 votes
18 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 in Java by Suresh
• 700 points
72,747 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,870 points
94 views
0 votes
1 answer

How can I Sort an ArrayList in Java

You can sort the ArrayList in 2 ...READ MORE

answered Apr 23, 2018 in Java by sharth
• 3,320 points
55 views
0 votes
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,280 points
42 views
0 votes
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,540 points
52 views
0 votes
2 answers

How to convert ArrayList<String> to String[] in Java

Try this:  String[] strArray = arrayList.toArray(new Stri ...READ MORE

answered 4 days ago in Java by Sirajul
• 19,670 points
62 views
+1 vote
3 answers

What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,190 points
271 views
+1 vote
3 answers

How to convert a List to an Array in Java?

Either: Foo[] array = list.toArray(new Foo[list.size()]); or: Foo[] array = ...READ MORE

answered Aug 7, 2018 in Java by Akrati
• 3,150 points
51 views
0 votes
3 answers

How to reverse a string in java?

public static String reverse(String s) { ...READ MORE

answered Aug 16, 2018 in Java by samarth295
• 2,190 points
73 views