GoingMyWay
GoingMyWay

Reputation: 17468

Java, java.util.HashMap cannot be cast to org.bson.BSONObject

I have been working wrote a MapReduce Program to implement word count with data store in MongoDB. I want to cast BSONObject to HashMap in Java, but it return the error

java.lang.Exception: java.lang.ClassCastException: java.util.HashMap cannot be cast to org.bson.BSONObject

And my code

BasicBSONObject result = new BasicBSONObject();
HashMap<String, Integer> mymap = new HashMap<String, Integer>();
[snippt]
for (BSONWritable val : values) {
{
    HashMap<String, Integer> temp = (HashMap<String, Integer>) val.getDoc().toMap();
    for (Map.Entry<String, Integer> entry :  temp.entrySet()) {
        if (mymap.containsKey(entry.getKey())) {
            mymap.put(entry.getKey(), entry.getValue()+1);
        }
        else {
            mymap.put(entry.getKey(), 1);
        }
    }

}
result.putAll((BSONObject)mymap);

I want to my mymap into result. Since mymap is a HashMap instance, I think putAll method is a choice.

How can I fix it? Thanks!

Upvotes: 2

Views: 6818

Answers (1)

Related Questions