Home > Net >  How to pass just the values of a list as arguments in Java
How to pass just the values of a list as arguments in Java

Time:04-01

I have a requirement where I need to pass the items of a list as arguments to a library function. This function receives arguments as String[] args. So something like myFunc(list[0], list[1], list[2]...). Is there a way to just extract the items of a list and pass them?

Specifics:

Code:

CsvSchema schema = csvMapper.typedSchemaFor(PersonDetailsCSVTemplate.class) 
.withHeader() 
.sortedBy("personNameHeader", "personAgeHeader",...) 
.withColumnSeparator(',') 
.withComments();

Here the sortedBy function needs multiple strings as arguments based on which it will do the sorting and although I have a list of strings received from csv header row, I am not sure how to pass them individually.

CodePudding user response:

You can convert your List<String> to a String[] with the toArray(IntFunction<T[]> generator) method that was added in Java 11:

String[] strings = list.toArray(String[]::new);

Or to pass it directly:

CsvSchema schema = csvMapper.typedSchemaFor(PersonDetailsCSVTemplate.class)
    .withHeader()
    .sortedBy(list.toArray(String[]::new))
    .withColumnSeparator(',')
    .withComments();

On Java 8, use the overload of toArray that takes an array:

CsvSchema schema = csvMapper.typedSchemaFor(PersonDetailsCSVTemplate.class)
    .withHeader()
    .sortedBy(list.toArray(new String[list.size()]))
    .withColumnSeparator(',')
    .withComments();

Or:

CsvSchema schema = csvMapper.typedSchemaFor(PersonDetailsCSVTemplate.class)
    .withHeader()
    .sortedBy(list.toArray(new String[0]))
    .withColumnSeparator(',')
    .withComments();

If the array is too small, it will create one of the necessary size, based on the element type of the array you pass in. That is why passing in a zero-length array will work.

CodePudding user response:

You mean your required function accept only String[] type as argument and you have List of item and you want to pass this list of item function, which you required?If so than you can use List of interface of toArray(); method For example:

List<String> list = Arrays.asList("A", "B", "C");
String[] array = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array));
  • Related