What is the easiest way to convert a HashMap into a 2D array?
Asked
Active
Viewed 2.4k times
5 Answers
15
HashMap map = new HashMap();
Object[][] arr = new Object[map.size()][2];
Set entries = map.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr[i][0] = mapping.getKey();
arr[i][1] = mapping.getValue();
i++;
}

nalo
- 998
- 2
- 8
- 12
-
-
See one-liner with Java 8 streams [here](https://stackoverflow.com/a/66106143/389489) – Somu Feb 10 '21 at 05:06
9
This can only be done when the types of both key and value are the same.
Given:
HashMap<String,String> map;
I can create an array from this map with this simple loop:
String[][] array = new String[map.size()][2];
int count = 0;
for(Map.Entry<String,String> entry : map.entrySet()){
array[count][0] = entry.getKey();
array[count][1] = entry.getValue();
count++;
}

Scharrels
- 3,055
- 25
- 31
8
How about
Object[][] array = new Object[][]{map.keySet.toArray(), map.entrySet.toArray()};
Or, to be more specific about the types, let's say they're Strings
: Set
's toArray
takes a hint argument, so that
String[][] array = new String[][]{map.keySet.toArray(new String[0]), map.entrySet.toArray(new String[0])};
Edit: I just realized a couple of days later that while this may work by chance, in general it shouldn't. The reason is the intermediate Set
; although it is "backed by the map", there seems to be no explicit guarantee that it will iterate in any particular order. Thus the key- and entry-arrays might not be in the same order, which is a disaster for sure!

Joonas Pulakka
- 36,252
- 29
- 106
- 169
-
I do like your approach as you're able to do it in one-liners. Yet, why are you using `map.keySet` and `map.entrySet` instead of `map.keySet()` and `map.entrySet()` – Qohelet Apr 03 '19 at 09:23
0
Using Java 8 stream:
@Test
void testMapToArray() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", 2);
Object[][] arr =
map.entrySet().stream()
.map(e -> new Object[]{e.getKey(), e.getValue()})
.toArray(Object[][]::new);
System.out.println(Arrays.deepToString(arr));
}
Output:
[[key1, value1], [key2, 2]]

Somu
- 3,593
- 6
- 34
- 44