2012-06-13 11 views
12

Come posso scaricare il contenuto di una Java HashMap (o qualsiasi altra), ad esempio per STDOUT?Come si esegue il dump dei contenuti di una mappa hash?

Per fare un esempio, supponiamo che ho un complesso di HashMap la seguente struttura:

(student1 => Map(name => Tim,   
        Scores => Map(math => 10, 
            physics => 20, 
            Computers => 30), 
        place => Miami, 
        ranking => Array(2,8,1,13), 
       ), 
student2 => Map ( 
        ............... 
        ............... 
       ), 
............................ 
............................ 
); 

quindi vorrei stamparlo sullo schermo al fine di avere un'idea sulla struttura dati. Sto cercando qualcosa di simile a var_dump() di PHP o a Dumper di Perl().

+0

Hai provato 'toString()'? –

risposta

20

Usa HashMap.toString() (docs here):

System.out.println("HASH MAP DUMP: " + myHashMap.toString()); 

In generale, utilizzare Object.toString() per scaricare i dati di questo tipo.

+0

Funziona bene tranne per gli array. Vedi una stampa qui, '{list_mem = {validate_data = {name = STRING, place = DONT_KNOW}, func = getMemList, elems = [I @ 973678}}'. Qui 'elems' è una matrice e i suoi valori non vengono stampati. –

0

Uso spesso una funzione come questa (potrebbe essere necessario espandere per consentire la stampa di altri tipi di oggetti all'interno di Map).

@SuppressWarnings("unchecked") 
private static String hashPP(final Map<String,Object> m, String... offset) { 
    String retval = ""; 
    String delta = offset.length == 0 ? "" : offset[0]; 
    for(Map.Entry<String, Object> e : m.entrySet()) { 
     retval += delta + "["+e.getKey() + "] -> "; 
     Object value = e.getValue(); 
     if(value instanceof Map) { 
      retval += "(Hash)\n" + hashPP((Map<String,Object>)value, delta + " "); 
     } else if(value instanceof List) { 
      retval += "{"; 
      for(Object element : (List)value) { 
       retval += element+", "; 
      } 
      retval += "}\n"; 
     } else { 
      retval += "["+value.toString()+"]\n"; 
     } 
    } 
    return retval+"\n"; 
} // end of hashPP(...) 

Così seguente codice

public static void main(String[] cmd) { 
    Map<String,Object> document = new HashMap<String, Object>(); 

    Map<String,Object> student1 = new LinkedHashMap<String, Object>(); 
    document.put("student1", student1); 
    student1.put("name", "Bob the Student"); 
    student1.put("place", "Basement"); 
    List<Integer> ranking = new LinkedList<Integer>(); 
    student1.put("ranking", ranking); 
    ranking.add(2); 
    ranking.add(8); 
    ranking.add(1); 
    ranking.add(13); 
    Map<String,Object> scores1 = new HashMap<String, Object>(); 
    student1.put("Scores", scores1); 
    scores1.put("math", "0"); 
    scores1.put("business", "100"); 

    Map<String,Object> student2= new LinkedHashMap<String, Object>(); 
    document.put("student2", student2); 
    student2.put("name", "Ivan the Terrible"); 
    student2.put("place", "Dungeon"); 

    System.out.println(hashPP(document)); 
} 

produrrà uscita

[student2] -> (Hash) 
    [name] -> [Ivan the Terrible] 
    [place] -> [Dungeon] 

[student1] -> (Hash) 
    [name] -> [Bob the Student] 
    [place] -> [Basement] 
    [ranking] -> {2, 8, 1, 13, } 
    [Scores] -> (Hash) 
    [math] -> [0] 
    [business] -> [100] 

nuovo. Potrebbe essere necessario modificare questo per le vostre esigenze particolari.

+0

Utilizzare decisamente 'StringBuilder' anziché la concatenazione. Inoltre, qual è il punto di 'offset' che è varargs? E il mix di parametri di tipo generici arbitrari, tipi grezzi e cast non sicuri? –

+0

1) Se si utilizza questa funzione per il debug occasionale, l'uso della concatenazione di stringhe non fa alcuna differenza. 2) Avendo variabile offset come varagrs evito di creare un'altra funzione hashPP (Map <,> m) {return hashPP (m, ""); } – Dmitri

+0

Inoltre, poiché utilizzo questa funzione per la stampa di debug, so che la maggior parte della mia chiave di codice è in genere una stringa e il valore è un oggetto generico o un'altra hashmap di natura simile, che segue quindi i lavori per la maggior parte dei casi. Per renderlo più generico si renderebbe anche chiave un oggetto. – Dmitri

1

Un buon modo per scaricare strutture di dati (ad esempio fatto di mappe nidificate, array e insiemi) è serializzandolo su JSON formattato. Ad esempio, utilizzando GSON (com.google.gson):

Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
System.out.println(gson.toJson(dataStructure)); 

Questo stamperà le strutture dati più complesse in un modo abbastanza leggibile.

Problemi correlati