Converting 'Arraylist≪String≫ to 'String[]' in Java

Best way to convert an ArrayList to a string

Java 8 introduces a String.join(separator, list) method; see Vitalii Federenko's answer.

Before Java 8, using a loop to iterate over the ArrayList was the only option:

DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

String listString = "";

for (String s : list)
{
listString += s + "\t";
}

System.out.println(listString);

In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here's a part of the disassembly of the bytecode from the for loop from the above program:

   61:  new #13; //class java/lang/StringBuilder
64: dup
65: invokespecial #14; //Method java/lang/StringBuilder."<init>":()V
68: aload_2
69: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: aload 4
74: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
77: ldc #16; //String \t
79: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
82: invokevirtual #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;

As can be seen, the compiler optimizes that loop by using a StringBuilder, so performance shouldn't be a big concern.

(OK, on second glance, the StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would probably yield better performance.)

In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.

Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of StringBuilder on each iteration. (Which I have noted previously.)

The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single StringBuilder object outside of the for loop.

Rewriting to the above code to:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

StringBuilder sb = new StringBuilder();
for (String s : list)
{
sb.append(s);
sb.append("\t");
}

System.out.println(sb.toString());

Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):

   // Instantiation of the StringBuilder outside loop:
33: new #8; //class java/lang/StringBuilder
36: dup
37: invokespecial #9; //Method java/lang/StringBuilder."<init>":()V
40: astore_2

// [snip a few lines for initializing the loop]
// Loading the StringBuilder inside the loop, then append:
66: aload_2
67: aload 4
69: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: pop
73: aload_2
74: ldc #15; //String \t
76: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
79: pop

So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration.

Converting 'ArrayList<String> to 'String[]' in Java

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

For example:

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

Convert ArrayList<String> to String[] array

Use like this.

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
System.out.println(s);

How to convert a String into an ArrayList?

Try something like

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
  • Arrays.asList documentation
  • String.split documentation
  • ArrayList(Collection) constructor documentation

Demo:

String s = "lorem,ipsum,dolor,sit,amet";

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

System.out.println(myList); // prints [lorem, ipsum, dolor, sit, amet]

This post has been rewritten as an article here.

cannot convert from ArrayList<String> to String[]

Clearly the ArrayList<String> array and String[] are incompatible types

Use toArray to return an array of the type contained within the collection and match the expected return type for the method getEmailsFromDB

return list.toArray(new String[array.size()]);

How to Convert arraylist<string> to string[]

You can do this for converting ArrayList to String[].

public SampleGridViewAdapter(Context context,ArrayList<String> urls) {
this.context = context;
this .urls=urls;
Log.i("DDDDDDDDDD",String.valueOf(urls));
String[] simpleArray = new String[urls.size()];
simpleArray = urls.toArray(simpleArray);
Log.i("GGGGGGGGGGG",String.valueOf(simpleArray));
}

OR you can also do this way -

public SampleGridViewAdapter(Context context,ArrayList<String> urls) {
this.context = context;
this .urls=urls;
Log.i("DDDDDDDDDD",String.valueOf(urls));
Object[] simpleArray = urls.toArray();

for(int i = 0; i < simpleArray.length ; i++){
Log.d("string is",(String)simpleArray[i]);
}
Log.i("GGGGGGGGGGG",String.valueOf(simpleArray));
}

How can I convert ArrayList<Object> to ArrayList<String>?

Since this is actually not a list of strings, the easiest way is to loop over it and convert each item into a new list of strings yourself:

List<String> strings = list.stream()
.map(object -> Objects.toString(object, null))
.collect(Collectors.toList());

Or when you're not on Java 8 yet:

List<String> strings = new ArrayList<>(list.size());
for (Object object : list) {
strings.add(Objects.toString(object, null));
}

Or when you're not on Java 7 yet:

List<String> strings = new ArrayList<String>(list.size());
for (Object object : list) {
strings.add(object != null ? object.toString() : null);
}

Note that you should be declaring against the interface (java.util.List in this case), not the implementation.

Best Way to Convert ArrayList to String in Kotlin

Kotlin has joinToString method just for this

list.joinToString()

You can change a separator like this

list.joinToString(separator = ":")

If you want to customize it more, these are all parameters you can use in this function

val list = listOf("one", "two", "three", "four", "five")
println(
list.joinToString(
prefix = "[",
separator = ":",
postfix = "]",
limit = 3,
truncated = "...",
transform = { it.uppercase() }
)
)

which outputs

[ONE:TWO:THREE:...]

Spring mvc arraylist auto binding converts into string array

When you post a form with a multiple select option, Spring parses the parameters in an array of Strings.

Let's take a closer look at your error message.

Line 1:

Failed to convert property value of type java.lang.String[] to required type java.util.ArrayList for property skills;

Spring parses the String[] from the URL parameters and doing:

String[] input = { "foo", "bar" };
ArrayList<String> skills = (ArrayList<String>) input;

is obviously going to fail, since Java doesn't automatically know how to typecast it. However, there are a few simple conversions built in, like String[] into List<String>, as shown here.

Line 2:

nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String[]] to required type [java.util.ArrayList] for property skills: no matching editors or conversion strategy found

You can teach Spring to convert basically anything into anything, if you define a proper conversion strategy. This works by building a Converter class to automatically convert A into B and then teaching Spring to use it. Here's another answer, that outlines how to do that.



Related Topics



Leave a reply



Submit