HashMap <object,boolean =“”> toString问题</object,>

时间:2011-04-01 21:18:33

标签: java hashmap tostring

我有一个HashMap类型的Map。

我正在尝试迭代地图,并且对于每个条目,布尔标志设置为true,我试图打印相应的键值。

我能够做到这一点。但是,它不打印String“key”值,而是打印String对象。我尝试使用.toString()函数进行强制转换。没有解决它。

非常感谢任何帮助。

感谢,S。

6 个答案:

答案 0 :(得分:5)

您希望迭代Map的entrySet:

Set< Map.Entry<String, Boolean> > es = map.entrySet();

这是一个集合,所以你可以迭代它:

for( Map.Entry<String, Boolean> v : es ) {
   if( v.getValue() ) { // auto-unboxing
       System.out.println(v.getKey());
   }
}

简化:

for( Map.Entry<String, Boolean> v : map.entrySet() ) {
   if( v.getValue() ) {
       System.out.println(v.getKey());
   }
}

答案 1 :(得分:2)

你可能想要这样的东西:

for(String key : map.keySet()){
  if(map.get(key)){
    System.out.println(key);
  }
}

答案 2 :(得分:1)

这应该有效:

Map<String, Boolean> myMap = new HashMap<String, Boolean>();
myMap.put("one", true);
myMap.put("second", false);

for (String key : myMap.keySet()) {
  if (myMap.get(key)) {
    System.out.println(key + " --> " + myMap.get(key));
  }
}

答案 3 :(得分:1)

你的后续建议你的Map中的值不是String类型,也不是重写toString的类型,这就是为什么当你调用toString时,你会得到一个像“com.f5.lunaui.emproto”这样的值。 .reports.Device_Sri @ 334003" 。

在Device_Sri中,您应该覆盖toString方法以返回所需的String:

@Override
public String toString() {
    return "em_device90-36";
}

当然,您可能希望从Device_Sri类的字段中计算值“em_device90-36”。

答案 4 :(得分:0)

private Map<String, Boolean> deviceChecked = new HashMap<String, Boolean>();
deviceChecked = checkMap;

Set entry = deviceChecked.entrySet();
    Iterator i = entry.iterator();
while(i.hasNext()){
    Map.Entry ent = (Map.Entry)i.next();
    if(ent.getValue()){
        result = result + (String)ent.getKey() + ", ";
    }
}
System.out.println("result is " +result);
return result;

我正在尝试仅在相应的布尔值为true时打印密钥。像上面的代码。在此,结果值不包含字符串,它将打印对象。 我应该将值打印为“em-device90-36”。但是,相反,我得到了这个印刷

  

com.f5.lunaui.emproto.reports.Device_Sri@334003

答案 5 :(得分:0)

要添加到其他答案,如果值为null,您将获得空指针异常。

if (e.getValue()) { ... }

这是因为该值为Boolean,并且将取消装箱到boolean。它相当于e.getValue().booleanValue()

如果要防止值为null,请使用

if (Boolean.TRUE.equals(e.getValue()) { ... }
相关问题