Printing HashMap In Java

后端 未结 15 1734
半阙折子戏
半阙折子戏 2020-11-28 19:32

I have a HashMap:

private HashMap example = new HashMap();

Now I would lik

15条回答
  •  没有蜡笔的小新
    2020-11-28 19:50

    If the map holds a collection as value, the other answers require additional effort to convert them as strings, such as Arrays.deepToString(value.toArray()) (if its a map of list values), etc.

    I faced these issues quite often and came across the generic function to print all objects using ObjectMappers. This is quite handy at all the places, especially during experimenting things, and I would recommend you to choose this way.

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    public static String convertObjectAsString(Object object) {
        String s = "";
        ObjectMapper om = new ObjectMapper();
        try {
            om.enable(SerializationFeature.INDENT_OUTPUT);
            s = om.writeValueAsString(object);
        } catch (Exception e) {
            log.error("error converting object to string - " + e);
        }
        return s;
    }
    

提交回复
热议问题