DEV Community

Thanaphoom Babparn
Thanaphoom Babparn

Posted on

4 1

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. ๐Ÿ˜„

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how theyโ€™re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

๐Ÿ› ๏ธ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more