HashMap<对象 ,布尔值>字符串问题对象>
我有一个 HashMap 类型的 Map。
我试图迭代地图,对于布尔标志设置为 true 的每个条目,我试图打印相应的键值。
我能够实现这一目标。但是,它不是打印字符串“键”值,而是打印字符串对象。我尝试使用 .toString() 函数来转换它。什么也解决不了。
任何帮助将不胜感激。
谢谢,S。
I am having a Map of type HashMap.
I am trying to iterate over the map and for every entry, for which the boolean flag is set to true, I am trying to print the corresponding key value.
I am able to achieve this. However, instead of printing the String "key" values, it prints String objects. I tried casting it, using the .toString() function. Nothing solved it.
Any help would be greatly appreciated.
Thanks,S.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您想要迭代Map的entrySet:
这是一个集合,因此您可以迭代它:
简化:
You want to iterate over the Map's entrySet:
That's a set, so you can iterate over it:
Simplifying:
您的后续建议表明您的 Map 中的值不是 String 类型,也不是覆盖 toString 的类型,这就是为什么当您调用 toString 时,您会得到类似“com.f5.lunaui.emproto.reports”的值。 Device_Sri@334003”。
在Device_Sri 中,您应该重写toString 方法以返回您想要的字符串:
当然,您可能希望从Device_Sri 类的字段中计算值“em_device90-36”。
Your followup suggests that the values in your Map are not of type String and are not of a type that has overridden toString, which is why, when you call toString, you get a value like "com.f5.lunaui.emproto.reports.Device_Sri@334003".
In Device_Sri, you should override the toString method to return the String you want:
Of course, you'll probably want to calculate the value "em_device90-36" from the fields of the Device_Sri class.
你可能想要这样的东西:
You probably want something like this:
这应该有效:
This should work:
要添加到其他答案,如果值为空,您将收到空指针异常。
这是因为该值是一个
Boolean
并且将被拆箱为boolean
。它相当于e.getValue().booleanValue()
。如果你想防止值为空,那么使用
To add to the other answers, you'll get a null pointer exception if the value is null.
This is because the value is a
Boolean
and will be unboxed to aboolean
. It's equivalent toe.getValue().booleanValue()
.If you want to guard against the value being null, then use
仅当相应的布尔值为 true 时,我才尝试打印密钥。就像上面的代码一样。在此,结果值不包含字符串,而是打印对象。
我应该将值打印为“em-device90-36”。但是,我却打印了这个
I am trying to print the key only if the corresopnding boolean value is true. Something like the code above. In this, the result value does not contain the string and it turn prints the object.
I should get the value to be printed as "em-device90-36". But, instead I get this printed