2

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);
        }
    }
4
  • Does the List contain numbers 15, 31 and 16? Commented May 14, 2015 at 18:24
  • it doesnt work with "return Map;" Commented May 14, 2015 at 18:25
  • I can enter Name and Key of objects in List Commented May 14, 2015 at 18:26
  • Capitalized Map is an interface, you might be having issues with that as well. Commented May 14, 2015 at 18:26

2 Answers 2

4

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());
}
Sign up to request clarification or add additional context in comments.

Comments

0

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()); }

2 Comments

It prints as in comment i answered upper. Problem is that for each object of list i need to call method that return its name
You need to override the toString() if you want it to display in a different way or iterate through the returned list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.