3

I'd like to convert the entrySet() of an Map<String, Statistic> to an array (or ArrayList).

I tried:

Map.Entry<String, Statistic>[] entries = statisticMap.entrySet().toArray(new Map.Entry<String, Statistic>[0]);

but this gives the compiler error: "Cannot create a generic array of Map.Entry"

Even this does not work, with same error:

Map.Entry<String, Statistic>[] entries = new Map.Entry<String, Statistic>[1];

But this works:

Map.Entry[] entries = new Map.Entry[1];

Any ideas how to create such a array or list?

AlexWien
  • 27,900
  • 6
  • 50
  • 80
  • possible duplicate of [How do you instantiate a Map.Entry array in Java?](http://stackoverflow.com/questions/8504045/how-do-you-instantiate-a-map-entryk-v-array-in-java) – Eran Jul 24 '14 at 20:29
  • The above anwer in the duplicate is less suitable than Peters answer below. – AlexWien Jul 24 '14 at 20:45

3 Answers3

5

If you're willing to get a list instead of an array, you can do this:

List<Map.Entry<String, Statistic>> list = new ArrayList<>(map.entrySet());

Using a list avoids the problems creating arrays of generics, and it also lets you use the "diamond operator" of Java 7 to avoid repeating the type arguments.

Stuart Marks
  • 120,620
  • 35
  • 192
  • 252
3

Any ideas how to create such a array or list?

You can do this, though it is ugly.

Map.Entry<String, Statistic>[] entries = 
                          (Map.Entry<String, Statistic>[]) new Map.Entry[num];
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
-1

Well, the root reason for complication is the broken Java design, compared to C#, where Array and List doesn't implement the same interface. So, any solution will be ugly (and with performance penalty).

If going ugly, personally I prefer explicit solutions, where at least you can see whats actually going on.

Therefore, my ugly version is:

Map.Entry<String, String>[] keys = new Map.Entry[map.entrySet().size()];

int index = 0;
for (Map.Entry<String, String> entry: map.entrySet()) {

     keys[index] = entry;
     index++;
}
Illidan
  • 3,761
  • 3
  • 34
  • 40