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.

原文链接:Transform List to Varargs in Java

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容