Java pass list of Strings to method
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. Show E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food): for x in food: print(x)fruits = ["apple", "banana", "cherry"] my_function(fruits) Try it Yourself »
This post will discuss how to convert a list of strings to a string array in Java. 1. Using List.toArray() methodWe can use the toArray(T[]) method to copy the list into a newly allocated string array. We can either pass a string array as an argument to the toArray() method or pass an empty string type array. If an empty array is passed, JVM will allocate memory for the string array. Please note that if no argument is passed to toArray(), it will return an Object array.
Download Run Code Output: 2. Using Java 8Java 8 provides another simple approach to convert a list of strings to a string array. Following are the steps: The following program demonstrates it:
Download Run Code Output: 3. Using Arrays.copyOf() methodWe can also use Arrays.copyOf() to copy the specified array to an array of the specified type.
Download Run Code Output: 4. Using System.arraycopy() methodWe can use System.arraycopy() that copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
Download Run Code Output: 5. Naive solutionThis post is incomplete without re-inventing the wheels. A naive approach uses regular for-loop to iterate over the list of strings and simply copy elements from a list to string array.
Download Run Code Output: That’s all about converting List of String to an array of Java String.
Thanks for reading. Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages. Like us? Refer us to your friends and help us grow. Happy coding 🙂 |