a_dzik
a_dzik

Reputation: 977

Collection to method parameters?

We have a method:

public void foo (String s1, String s2, String s3) { 
    ...
}

And a collection of choice. Maybe hashmap, maybe list, doesn't matter.

Is there a way to "convert" collection to method paramterers? Something like:

public void foo (getParamters(map)) { ... }

Yes, ofcourse I could do

public void foo (map.get(0), map.get(1), map.get(3)) { ... }

but I'm thinking about something a bit more automatic, that could help me with a bigger problem.

Upvotes: 3

Views: 2266

Answers (3)

user3145373 ツ
user3145373 ツ

Reputation: 8146

You can use varargs, it allows the method to accept zero or multiple arguments. If we don't know how many argument we will have to pass in the method, varargs is the better approach.

Syntax:

return_type method_name(data_type... variableName){
  // code snippet
}

Example :

public void varargsMethod(String... values){          
    for(String s:values){  
       System.out.println(s);  
    }  
}

Running example

Upvotes: 0

Georgi Peltekov
Georgi Peltekov

Reputation: 116

You can use varargs for example:

public static void main(String[] args) {
    test("1", "2");
    test("1", "2", "3");

}

public static void test(String ...args){
    for (int i = 0; i < args.length; i++) {
        //do something
    }
}

Upvotes: 1

Eran
Eran

Reputation: 393781

You can convert the Collection to an array and pass the array to the method :

public void foo (String... s) { 
    ...
}

...

String[] arr = map.keySet().toArray (new String[0]);
foo (arr);

Since you don't know beforehand the number of elements in your Collection, declaring the method with varargs makes more sense then a fixed number of arguments as you have in foo (String s1, String s2, String s3).

Upvotes: 5

Related Questions