Java HashMap 内容到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35596567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:20:22  来源:igfitidea点击:

Java HashMap content to String

javahashmap

提问by CeZet

Please read comments before You downmark!

请在您降分之前阅读评论!

I want convert content of HashMapto Stringas converting ArrayListto Stringusing Arrays.toString(arrayList).

我想将HashMapto 的内容String转换ArrayListStringusing 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:

我是否必须迭代并使用它附加它Iterator?例如:

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>

我认为这是不同的,因为pair <String, ArrayList>not<String, Integer>

回答by Bahramdun Adil

You can use toString()of the Map:

您可以使用toString()Map

String content = objectMap.toString();

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

Map覆盖该toString()方法,因此您可以轻松获取地图的内容。

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

所以这意味着它运作良好