Pretty-print a Map in Java

前端 未结 16 934
傲寒
傲寒 2020-12-04 10:11

I am looking for a nice way to pretty-print a Map.

map.toString() gives me: {key1=value1, key2=value2, key3=value3}

I

相关标签:
16条回答
  • 2020-12-04 10:39

    I guess something like this would be cleaner, and provide you with more flexibility with the output format (simply change template):

        String template = "%s=\"%s\",";
        StringBuilder sb = new StringBuilder();
        for (Entry e : map.entrySet()) {
            sb.append(String.format(template, e.getKey(), e.getValue()));
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1); // Ugly way to remove the last comma
        }
        return sb.toString();
    

    I know having to remove the last comma is ugly, but I think it's cleaner than alternatives like the one in this solution or manually using an iterator.

    0 讨论(0)
  • 2020-12-04 10:44

    Using Java 8 Streams:

    Map<Object, Object> map = new HashMap<>();
    
    String content = map.entrySet()
                        .stream()
                        .map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
                        .collect(Collectors.joining(", "));
    
    System.out.println(content);
    
    0 讨论(0)
  • 2020-12-04 10:46

    I prefer to convert the map to a JSON string it is:

    • a standard
    • human readable
    • supported in editors like Sublime, VS Code, with syntax highlighting, formatting and section hide/show
    • supports JPath so editors can report exactly which part of the object you have navigated to
    • supports nested complex types within the object

      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      
      public static String getAsFormattedJsonString(Object object)
      {
          ObjectMapper mapper = new ObjectMapper();
          try
          {
              return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
          }
          catch (JsonProcessingException e)
          {
              e.printStackTrace();
          }
          return "";
      }
      
    0 讨论(0)
  • 2020-12-04 10:47

    Apache libraries to the rescue!

    MapUtils.debugPrint(System.out, "myMap", map);
    

    All you need Apache commons-collections library (project link)

    Maven users can add the library using this dependency:

    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题