开发者

Problem in accessing elements from google HashMultimap

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");
    开发者_StackOverflow中文版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.


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.


Use the instanceof keyword.

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜