Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 440
a_dzik Avatar asked Nov 24 '25 18:11

a_dzik


2 Answers

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).

like image 173
Eran Avatar answered Nov 27 '25 07:11

Eran


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
    }
}
like image 20
Georgi Peltekov Avatar answered Nov 27 '25 07:11

Georgi Peltekov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!