Transform List to Varargs in Java

tpbabparn

Thanaphoom Babparn

Posted on June 1, 2021

Transform List to Varargs in Java

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it. This is how we can use List as argument of method that received varargs.

Thank you very much for reading. 😄

💖 💪 🙅 🚩
tpbabparn
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