6

Please read comments before You downmark!

I want convert content of HashMap to String as converting ArrayList to String using Arrays.toString(arrayList).

Is it possible ? There is easy way to do this?

Do I must have to iteration and appending it using Iterator ? As example:

HashMap<String, ArrayList<MyObject>> objectMap = new HashMap<String, ArrayList<>>();

//.... put many items to objectMap

Iterator it = objectMap.entrySet().iterator();

while(it.hasNext()){
  Map.Entry pairs = (Map.Entry) it.next();
  System.out.println(pairs.getKey() + " = " + pairs.getValue());
}

I think that it is different because of pair <String, ArrayList> not <String, Integer>

0

1 Answer 1

10

You can use toString() of the Map:

String content = objectMap.toString();

Map overrides the toString() method, so you can easily get the contents of map.

I should give an example:

public static void main(String[] args) throws Exception {
    HashMap<String, List<MyObject>> objectMap = new HashMap<>();
    List<MyObject> list = new ArrayList<>();
    list.add(new MyObject(12, 12));
    objectMap.put("aaaa", list);
    String content = objectMap.toString();
    System.out.println("content = " + content);
}

private static class MyObject {
    int min;
    int max;

    public MyObject(int max, int min) {
        this.max = max;
        this.min = min;
    }

    @Override
    public String toString() {
        return "MyObject{" +
                "max=" + max +
                ", min=" + min +
                '}';
    }
}

And it is the output:

content = {aaaa=[MyObject{max=12, min=12}]}

So it means it works well

Sign up to request clarification or add additional context in comments.

19 Comments

Nope, it don't work.
What is the reason of don't work?
It return bad String, not content but strange String about package where it from.
This is the reason: public final String toString() { return key + "=" + value; }. If value is an object, its toString() is not called
No, this problem is not belongs to Serializable
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.