Abhishek Abhishek - 3 months ago 6
Java Question

Variable number of list (ArrayList) as an argument to method

There is a way in Java to handle variable number of String arguments like

public void returnString(String...args){
//some code
}
// calling it
returnString("abc","def","klm")


I wanted to know if the same can be applied to Collections.

If it does not, what is the alternative. I read that array of List is not possible, so wondering how this might work.

//Sample code of what I am trying to do
public void returnList(List...args){
//some code
}

Answer

I don't know where is problem.... But here is example:

import java.util.ArrayList;
import java.util.List;

public class Main {

  public static void tryIt(List... lists) {
    System.out.println("You insert " + lists.length + " lists.");
  }
    public static void main(String[] args) {
      List<String> listStrings = new ArrayList<>();
      listStrings.add("TEST");
      List<Integer> listInteger = new ArrayList<>();
      listInteger.add(1);
      tryIt(listStrings);
      tryIt(listStrings, listInteger);
    }
}

Result:

You insert 1 lists.
You insert 2 lists.

Access to arrays example:

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void tryIt(List... lists) {
    System.out.println("You insert " + lists.length + " lists.");
    if (lists.length>2)
      for (Object obj : lists[2]) {
        System.out.println(obj);
      }
  }
  public static void main(String[] args) {
    List<String> listStrings = new ArrayList<>();
    listStrings.add("TEST");
    List<Integer> listInteger = new ArrayList<>();
    listInteger.add(1);
    List<String> anotherStringList = new ArrayList<>();
    anotherStringList.add("First value.");
    anotherStringList.add("Second value.");
    anotherStringList.add("Third value.");
    tryIt(listStrings);
    tryIt(listStrings, listInteger);
    tryIt(listInteger, listStrings, anotherStringList);
    }
}

Output:

You insert 1 lists.
You insert 2 lists.
You insert 3 lists.
First value.
Second value.
Third value.