Printing HashMap In Java

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

I have a HashMap:

private HashMap example = new HashMap();

Now I would lik

相关标签:
15条回答
  • 2020-11-28 19:49

    Assuming you have a Map<KeyType, ValueType>, you can print it like this:

    for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
        System.out.println(entry.getKey()+" : "+entry.getValue());
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-28 19:51

    A simple way to see the key value pairs:

    Map<String, Integer> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 2);
    System.out.println(Arrays.asList(map)); // method 1
    System.out.println(Collections.singletonList(map)); // method 2
    

    Both method 1 and method 2 output this:

    [{b=2, a=1}]
    
    0 讨论(0)
  • 2020-11-28 19:53

    Worth mentioning Java 8 approach, using BiConsumer and lambda functions:

    BiConsumer<TypeKey, TypeValue> consumer = (o1, o2) -> 
               System.out.println(o1 + ", " + o2);
    
    example.forEach(consumer);
    

    Assuming that you've overridden toString method of the two types if needed.

    0 讨论(0)
  • 2020-11-28 19:53

    For me this simple one line worked well:

    Arrays.toString(map.entrySet().toArray())
    
    0 讨论(0)
  • 2020-11-28 19:53

    I did it using String map (if you're working with String Map).

    for (Object obj : dados.entrySet()) {
        Map.Entry<String, String> entry = (Map.Entry) obj;
        System.out.print("Key: " + entry.getKey());
        System.out.println(", Value: " + entry.getValue());
    }
    
    0 讨论(0)
提交回复
热议问题