开发者

HashMap<Object, Boolean> toString problem

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, i开发者_如何学Gonstead 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.


You want to iterate over the Map's entrySet:

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

That's a set, so you can iterate over it:

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

Simplifying:

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


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:

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

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:

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


This should work:

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));
  }
}


To add to the other answers, you'll get a null pointer exception if the value is null.

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

This is because the value is a Boolean and will be unboxed to a boolean. It's equivalent to e.getValue().booleanValue().

If you want to guard against the value being null, then use

if (Boolean.TRUE.equals(e.getValue()) { ... }


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;

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜