J'ai besoin de convertir un HashMap<String, Object>en tableau; quelqu'un pourrait-il me montrer comment c'est fait?
J'ai besoin de convertir un HashMap<String, Object>en tableau; quelqu'un pourrait-il me montrer comment c'est fait?
Réponses:
hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values
Il convient de noter que l'ordre des deux tableaux peut ne pas être le même, voir la réponse oxbow_lakes pour une meilleure approche pour l'itération lorsque la paire clé / valeurs est nécessaire.
Setet les valeurs en a Collection. Bien qu'ils soient techniquement convertis en tableaux (et répondent à votre question), le concept de la paire clé-valeur a été perdu - c'est pourquoi il s'agit d'une réponse très trompeuse (et dangereuse) ....
Si vous voulez les clés et les valeurs, vous pouvez toujours le faire via entrySet:
hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]
À partir de chaque entrée, vous pouvez (bien sûr) obtenir à la fois la clé et la valeur via les méthodes getKeyetgetValue
{key, value}[]par opposition àkey[], value[]
Si vous avez HashMap<String, SomeObject> hashMapalors:
hashMap.values().toArray();
Reviendra un Object[]. Si à la place vous voulez un tableau du type SomeObject, vous pouvez utiliser:
hashMap.values().toArray(new SomeObject[0]);
values()au lieu de keySet()pour un tableau de SomeObject.
Pour garantir le bon ordre pour chaque tableau de clés et de valeurs, utilisez ceci (les autres réponses utilisent des individus Setqui n'offrent aucune garantie quant à l'ordre.
Map<String, Object> map = new HashMap<String, Object>();
String[] keys = new String[map.size()];
Object[] values = new Object[map.size()];
int index = 0;
for (Map.Entry<String, Object> mapEntry : map.entrySet()) {
keys[index] = mapEntry.getKey();
values[index] = mapEntry.getValue();
index++;
}
Une alternative à la suggestion CrackerJacks, si vous voulez que le HashMap maintienne l'ordre, vous pouvez envisager d'utiliser un LinkedHashMap à la place. Pour autant que je sache, sa fonctionnalité est identique à celle d'un HashMap, mais c'est FIFO donc il maintient l'ordre dans lequel les éléments ont été ajoutés.
J'ai utilisé presque la même chose que @kmccoy, mais au lieu d'un, keySet()j'ai fait ceci
hashMap.values().toArray(new MyObject[0]);
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
Object[][] twoDarray = new Object[map.size()][2];
Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();
for (int row = 0; row < twoDarray.length; row++) {
twoDarray[row][0] = keys[row];
twoDarray[row][1] = values[row];
}
// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
for (int j = 0; j < twoDarray[i].length; j++) {
System.out.println(twoDarray[i][j]);
}
}
Pour obtenir dans un tableau à une dimension.
String[] arr1 = new String[hashmap.size()];
String[] arr2 = new String[hashmap.size()];
Set entries = hashmap.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr1[i] = mapping.getKey().toString();
arr2[i] = mapping.getValue().toString();
i++;
}
Pour entrer dans un tableau à deux dimensions.
String[][] arr = new String[hashmap.size()][2];
Set entries = hashmap.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr[i][0] = mapping.getKey().toString();
arr[i][1] = mapping.getValue().toString();
i++;
}
Si vous utilisez Java 8+ et avez besoin d'une version 2 dimensions Array, peut-être pour les fournisseurs de données TestNG, vous pouvez essayer:
map.entrySet()
.stream()
.map(e -> new Object[]{e.getKey(), e.getValue()})
.toArray(Object[][]::new);
Si vos Objects sont des Strings et que vous en avez besoin String[][], essayez:
map.entrySet()
.stream()
.map(e -> new String[]{e.getKey(), e.getValue().toString()})
.toArray(String[][]::new);
Vous pouvez aussi essayer ceci.
public static String[][] getArrayFromHash(Hashtable<String,String> data){
String[][] str = null;
{
Object[] keys = data.keySet().toArray();
Object[] values = data.values().toArray();
str = new String[keys.length][values.length];
for(int i=0;i<keys.length;i++) {
str[0][i] = (String)keys[i];
str[1][i] = (String)values[i];
}
}
return str;
}
Ici, j'utilise String comme type de retour. Vous pouvez le changer pour le type de retour requis par vous.
HashMap()mais votre solution concerne Hashtable()... Il y a des différences entre eux
@SuppressWarnings("unchecked")
public static <E,T> E[] hashMapKeysToArray(HashMap<E,T> map)
{
int s;
if(map == null || (s = map.size())<1)
return null;
E[] temp;
E typeHelper;
try
{
Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
Entry<E, T> iK = iterator.next();
typeHelper = iK.getKey();
Object o = Array.newInstance(typeHelper.getClass(), s);
temp = (E[]) o;
int index = 0;
for (Map.Entry<E,T> mapEntry : map.entrySet())
{
temp[index++] = mapEntry.getKey();
}
}
catch (Exception e)
{
return null;
}
return temp;
}
//--------------------------------------------------------
@SuppressWarnings("unchecked")
public static <E,T> T[] hashMapValuesToArray(HashMap<E,T> map)
{
int s;
if(map == null || (s = map.size())<1)
return null;
T[] temp;
T typeHelper;
try
{
Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
Entry<E, T> iK = iterator.next();
typeHelper = iK.getValue();
Object o = Array.newInstance(typeHelper.getClass(), s);
temp = (T[]) o;
int index = 0;
for (Map.Entry<E,T> mapEntry : map.entrySet())
{
temp[index++] = mapEntry.getValue();
}
}
catch (Exception e)
{return null;}
return temp;
}
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);