在 Java 中打印 HashMap [英] Printing HashMap In Java

查看:25
本文介绍了在 Java 中打印 HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HashMap:

private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, TypeValue>();

现在我想遍历所有值并打印它们.

Now I would like to run through all the values and print them.

我是这样写的:

for (TypeValue name : this.example.keySet()) {
    System.out.println(name);
}

它似乎不起作用.

有什么问题?

另一个问题:这个集合是基于零的吗?我的意思是如果它有 1 个键和值,大小是 0 还是 1?

Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?

推荐答案

keySet() 只从你的哈希映射中返回一组键,你应该迭代这个键集并从哈希映射中获取值使用这些键.

keySet() only returns a set of keys from your hash map, you should iterate this key set and the get the value from the hash map using these keys.

在您的示例中,哈希映射键的类型是 TypeKey,但您在通用 for-loop 中指定了 TypeValue,因此它无法编译.您应该将其更改为:

In your example, the type of the hash map's key is TypeKey, but you specified TypeValue in your generic for-loop, so it cannot be compiled. You should change it to:

for (TypeKey name: example.keySet()) {
    String key = name.toString();
    String value = example.get(name).toString();
    System.out.println(key + " " + value);
}

Java8 更新:

example.entrySet().forEach(entry -> {
    System.out.println(entry.getKey() + " " + entry.getValue());
});


如果不需要打印key值,只需要hash map值,可以参考别人的建议.


If you don't require to print key value and just need the hash map value, you can use others' suggestions.

另一个问题:这个集合是零基吗?我的意思是如果它有 1 个键和值,它的大小是 0 还是 1?

Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?

keySet() 返回的集合是一个 设置.您无法使用索引从集合中获取值,因此它不是从零开始还是从一开始的问题.如果你的hash map只有一个key,返回的keySet()里面会有一个条目,大小为1.

The collection returned from keySet() is a Set. You cannot get the value from a set using an index, so it is not a question of whether it is zero-based or one-based. If your hash map has one key, the keySet() returned will have one entry inside, and its size will be 1.

这篇关于在 Java 中打印 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆