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.
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).
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With