如何获取MultiMap值的元素索引

时间:2017-01-11 10:29:05

标签: java apache-commons multimap

我想检查元素“Item Two”是否在MultiMap的值中获取该元素的索引,下面是我的代码。

import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;

 import org.apache.commons.collections.MultiMap;
 import org.apache.commons.collections.map.MultiValueMap;

 public class Test {
    public static void main(String args[]) {
        MultiMap mhm = new MultiValueMap();
        String key ="";
        key = "Group One";
        mhm.put(key, "Item One");
        mhm.put(key, "Item Two");
        mhm.put(key, "Item Three");

       key = "Group Two";
       mhm.put(key, "Item Four");
       mhm.put(key, "Item Five");

       Set keys = mhm.keySet();
       for (Object k : keys) {
           System.out.println("+k+“ : "+mhm.get(k)+")");
           List benefit = new ArrayList();
           benefit.add(mhm.get(k));
           System.out.println("+value at is+“ : "+benefit.contains("Item One")+")");
       } 
   }    
} 

输出是:

mhm-keys : [Item One, Item Two, Item Three]
value at is : false
mhm-keys : [Item Four, Item Five]
value at is : false

请你帮忙,因为我不能使用除MultiMap以外的其他东西

1 个答案:

答案 0 :(得分:1)

首先,不推荐使用MultiValueMap,您应该使用MultiValuedMap。 https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiValuedMap.html

MultiValuedMap<String, String> mhm = new ArrayListValuedHashMap<String, String>();

但是如果你想使用已弃用的MultiValueMap,那对我来说很好。对于两者,您可以使用以下内容:

mhm.containsValue(value);

你也可以使用:

List<String> itemsWithKey = mhm.get(key);
System.out.println(itemsWithKey.contains(value)); 

<强>更新 这对我有用:

MultiMap mhm = new MultiValueMap();
String key ="";
key = "Group One";
mhm.put(key, "Item One");
mhm.put(key, "Item Two");
mhm.put(key, "Item Three");

key = "Group Two";
mhm.put(key, "Item Four");
mhm.put(key, "Item Five");

System.out.println(mhm.containsValue("Item One"));
System.out.println(mhm.containsValue("Item Nine"));

返回:

true
false

更新2 这将检查&#34;第四项&#34;在所有键中并为每个键返回true / false

MultiMap mhm = new MultiValueMap();
String key ="";
key = "Group One";
mhm.put(key, "Item One");
mhm.put(key, "Item Two");
mhm.put(key, "Item Three");

key = "Group Two";
mhm.put(key, "Item Four");
mhm.put(key, "Item Five");


Set<String> keys = mhm.keySet();

String itemToLookFor = "Item Four";

for(String k : keys) {
    List<String> itemsWithKey = (List<String>) mhm.get(k);
    boolean doesExists = itemsWithKey.contains(itemToLookFor);
    System.out.println("does " + itemToLookFor + " exists for key " + k + ": " +doesExists); 
}

结果是:

does Item Four exists for key Group One: false
does Item Four exists for key Group Two: true