Convert String array to ArrayList
Use this code for that,
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class StringArrayTest {
public static void main(String[] args) {
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);
for (String e : wordList) {
System.out.println(e);
}
}
}
Convert array of strings to Liststring
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
How can I convert String[] to ArrayListString
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
converting array of strings to ArrayListString
Use the method Arrays.asList()
from the Arrays
class. It will return a List
of the correct generic type (String
in this case):
List<String> list = Arrays.asList(logsSplitFromUrdu);
If you absolutely need an ArrayList<String>
and a List<String>
won't do, then write one additional line after the previous one:
ArrayList<String> arraylist = new ArrayList<String>(list);
Converting 'ArrayListString 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 array of Strings to list of Integers?
You only need to stream once.
Instead of using int Integer::parseInt(String s)
, you should use Integer Integer::valueOf(String s)
, so you don't have to call boxed()
or rely on auto-boxing.
Then use collect(Collectors.toList())
directly, instead of creating intermediate array first.
List<Integer> allAnswerList = Arrays.stream(allAnswers) // stream of String
.map(Integer::valueOf) // stream of Integer
.collect(Collectors.toList());
C# - Convert String array to String List
There are two options.
Using LINQ ToList()
extension method - add using System.Linq;
to the top of your source file and then do:
var list = array.ToList();
Second option is to directly initialize the list via the constructor:
var list = new List<string>(array);
There is no difference in performance between these two approaches, both will take linear time relative to the number of items in the array (O(N)
).
How to convert an array of Strings to a list
You dont have to convert your Array of String objects to make the List work. You should describe your error pasting it along with your code to get helped faster. So, this is my assumption of your concept of error.
The Array type is fine, but however, his Elements, in this case the strings, need to be identified. This means you have to conform your String to the Identifiable protocol, and providing an id property which must be unique (a simple UUID object will do the trick).
In your code, the function getListOfAlphabets returns an array of Strings which cannot be used. If you were to use a [ListOfPeripherals] array that would work because it conforms to the protocol. I think you got a bit of confusion and you are basically returning an array of wrong type.
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.
Related Topics
How to Capitalize First Letter of First Name and Last Name in C#
In What Areas Might the Use of F# Be More Appropriate Than C#
Use Local Images in Webbrowser Control
Importing Excel into a Datatable Quickly
How to Generate Unique Public and Private Key via Rsa
Entity Framework Queryable Async
How to Test Your Request.Querystring[] Variables
The Bare Minimum Needed to Write a Msmq Sample Application
How to Use System.Net.Httpclient to Post a Complex Type
How to Get the Last Four Characters from a String in C#
How to Highlight Wrapped Text in a Control Using the Graphics
How to Apply a General Rule for Remapping All Property Names When Serializing with JSON.Net
C# - Which Is the Best Alternative to 'Switch on Type'