views:

95

answers:

2

I am using below code to get & process value from google HashMultimap

    HashMultimap hmm = new HashMultimap();
    HashMultimap hmm2 = new HashMultimap();
    Element ele;
:
    hmm2.put("name","Amit");
    hmm.put("Amit",ele);
    hmm.put("rohit",hmm2);
 :   
    Iterator itr =  hmm.keys().iterator();
    String ky = (String) itr.next();
    System.out.println(hmm.get(ky));
    ky = (String) itr.next();
    System.out.println(hmm.get(ky));

In above code, if map element(or entry) is Element type then i want to do some operation. If it is HashMultimap type then do some other operation. How can i check and pass the object to another function.

+1  A: 

Use the instanceof keyword.

Like so:
if (item instanceof Element) //Do things

Woot4Moo
I already had tried. it doesnt work
articlestack
can you please post the code you used with instanceof?
Woot4Moo
If you asking to me then it is complete code. if you are asking to @Woot4Moo then i suppose he is taking item of Object type
articlestack
+1  A: 

Since this is a HashMultimap which is also a SetMultimap, when you call hmm.get(ky) the value returned is going to be a Set of all the values for that key. You should then be able to iterate through each of the values in the Set and use instanceof on those values. If there are not going to be multiple values for each key, you shouldn't be using a Multimap to begin with and should just use normal HashMap.

    HashMultimap hmm = HashMultimap.create();
    HashMultimap hmm2 = HashMultimap.create();
    Element ele = new Element();
    hmm2.put("name", "Amit");
    hmm.put("Amit", ele);
    hmm.put("rohit", hmm2);
    Iterator itr = hmm.keys().iterator();
    String ky = (String) itr.next();

    Set elements = hmm.get(ky);
    Iterator elementsItr = elements.iterator();
    Object val = elementsItr.next();
    if (val instanceof Element) {
        doElementStuff((Element) val);
    }

    ky = (String) itr.next();
    elements = hmm.get(ky);
    elementsItr = elements.iterator();
    val = elementsItr.next();
    if (val instanceof Element) {
        doElementStuff((Element) val);
    }

The key point is that calling get() on a HashMultimap returns a Set of values and not a single value.

Paul Blessing
Are you talking to access value like `SetMultimap o = (SetMultimap) hmm.get(ky);`. It gives runtime error.
articlestack
Updated answer to try and clarify further.
Paul Blessing