简体   繁体   中英

Java pass Map to pair of varargs

Doing something like this with a normal array works:

public class TestVarArgs {
    public static void main(String[] args) {
        int[] array = new int[4];
        for (int i = 0; i < array.length; i++) {
            System.out.println(i);
        }
        testThis(array);
    }
    public static void testThis(int... args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(i);
        }
    }
}

Now how can I do this with maps?

I want to pass a map to a method that receives varargs of pairs.

Passing a Map to varargs of Entry.Map does not work.

Java varargs are equivalent to arrays, with compiler support that makes arrays behind the scene when calling the method.

If your method takes, say,

void myMethod(Map.Entry<String,String>>... args)

it is the same as

void myMethod(Map.Entry<String,String>>[] args)

so you could call it by inserting a conversion to array, like this:

Map<String,String> myMap = ...
...
myMethod((Entry<String,String>[])myMap.entrySet().toArray(new Map.Entry[myMap.size()]));

You can't pass a Collection to a varargs argument.
I think the easiest way is to create an array of key from the key set.

Map<K, V> aMap ;
Set<K> keySet = aMap.keySet();
K[] keyArray = keySet.toArray(new K[keySet.size()]);

aMethodWithVarargs(keyArray);

Of course, you can do this with the set of Entry.Map

Map<K, V> aMap ;
Set<Entry.Map<K, V>> entrySet = aMap.entrySet();
Entry.Map<K, V>[] entryArray = keySet.toArray(new Entry.Map<K, V>[keySet.size()]);

aMethodWithVarargs(entryArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM