Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an entrySet to an array

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?

like image 822
AlexWien Avatar asked Oct 21 '25 04:10

AlexWien


1 Answers

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.

like image 75
Stuart Marks Avatar answered Oct 23 '25 17:10

Stuart Marks



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!