简体   繁体   中英

Printing a HashMap that contains of String and List of Objects

How can I print a HashMap that containts of String and List of Objects?

HashMap<String, List<Object>> Map = new HashMap<String, List<Object>>();

Each object has a name and a key value so I need to get something like:

StringFirst = [ firstObject 15, second object 31, thirdobject 16]
StringSecond = [ fourthObject 15, fifthObject 31, sixthObject 16]

    public static class Graph {

    public class Edge extends Graph {
        String edgeName;
        int time;

        Edge(String edgeName, int time){
            this.edgeName = edgeName;
            this.time = time;
        }

        public void Out(){
            System.out.println(this.edgeName);
            System.out.println(this.time);
        }
    }

Try this out for printing the map:

for(Map.Entry<String, ArrayList<Edge>> e : map.entrySet()){
   for(Edge e1 : e.getValue())
      System.out.println(e.getKey() + " = "+ e1.Out());
}

The easiest way to iterate through a map would be to use the keyset.

for(String key: map.keyset()) { System.out.println(key + " = " + map.get(key)); }

On the .get(key) you may need to handle it differently, or iterate through the returned list

Alternately this is functionally the same,

for(Map.Entry e : map.entrySet()) { System.out.println(e.getKey() + " = "+ e.getValue()); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM