HashSet - 如何搜索

时间:2018-01-08 20:34:57

标签: java hashmap hashset

我有一个HashSet((的字符串和列表((两个字符串的)hashmap)的散列图))

HashSet<HashMap<String1,List<HashMap<String2,HashMap<String3,String4>>>>>

现在,我需要使用String输入(StrA和StrB)进行搜索,这应该搜索HashSet

  • STRA - &GT;字符串1
  • STRB - &GT; String2的

它应该返回String 3和String 4的hashMap。

这就是我的尝试。

HashSet<HashMap<String,List<HashMap<String,HashMap<String,String>>>>> ObjList;

public void getElement(String strA, String strB) {
    if(ObjList.contains(strA) && ObjList.contains(strB))
        System.out.println("Yes");
}

2 个答案:

答案 0 :(得分:1)

除了迭代外部Set和内部List(未经测试)之外别无选择:

HashSet<HashMap<String1,List<HashMap<String2,HashMap<String3,String4>>>>> outer = //...

HashMap<String3,String4> result =
   outer.stream()
        .findFirst(map1-> map1.containsKey(string1))
        .get()
        .stream()
        .findFirst(map2-> map2.containsKey(string2))
        .get();

答案 1 :(得分:1)

使用Streams的解决方案是:

HashSet<HashMap<String, List<HashMap<String, HashMap<String, String>>>>> fooSet = //;
String string1 = "string1";
String string2 = "string2";
HashMap<String, String> mapFound;


mapFound = fooSet.stream()                       // iterate over HashSet
       .filter(map -> map.containsKey(string1))  // keep maps that contains string1
       .findFirst()                              // take first map that match
       .orElseGet(HashMap::new)                  // take it really (or create new Map)
       .getOrDefault(string1, new ArrayList<>()) // take the List associated as value,or new List if not exists
       .stream()                                 // iterate over the list
       .filter(map -> map.containsKey(string2))  // keep maps that contains string2
       .findFirst()                              // take first map that match
       .orElseGet(HashMap::new)                  // take it really (or create new Map)
       .getOrDefault(string2, new HashMap<>());  // take HashMap associated as value, or new Map if not found

使用经典for each循环的解决方案是:

HashMap<String, String> mapFound;

for (HashMap<String, List<HashMap<String, HashMap<String, String>>>> map : fooSet) {
    if (map.containsKey(string1)) {
        List<HashMap<String, HashMap<String, String>>> list = map.get(string1);
        for(HashMap<String, HashMap<String, String>> map2 : list){
            if(map2.containsKey(string2)){
                mapFound = map2.get(string2);
            }
        }
    }
}