Transform List to Varargs in Java
Thanaphoom Babparn
Posted on June 1, 2021
Hello everyone 😁. For this article we will be transform List to Varargs.
Firstly, I want to show example of varargs in argument of method.
Normally, the varargs is represent as a iterator type that you can loop each element.
class Main {
public static void main(String args[]) {
System.out.println(concatString("Hello", "world!"));
}
public static String concatString(String... words) {
StringBuilder sb = new StringBuilder();
for (String str : words) {
sb.append(str);
sb.append(" ");
}
return sb.toString().trim();
}
}
But if you seen some library, They receive varargs as a parameter too!. So if you have list of data, you can transform it to array and thrown it to that method.
This is example of code that will show you how to transform it. ✌
import java.util.List;
class Main {
public static void main(String args[]) {
List<String> words = List.of("Hello", "world!");
String result = concatString(words.toArray(new String[words.size()]));
System.out.println(result);
}
public static String concatString(String... words) {
StringBuilder sb = new StringBuilder();
for (String str : words) {
sb.append(str);
sb.append(" ");
}
return sb.toString().trim();
}
}
That's it. This is how we can use List as argument of method that received varargs.
Thank you very much for reading. 😄
💖 💪 🙅 🚩
Thanaphoom Babparn
Posted on June 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
tailwindcss Implementing Dark Mode and Theme Switching using Tailwind v4 and Next.js
November 29, 2024