我要搜索地图中是否存在一个值 我有这样的地图
Map<String, Object> eMap = new HashMap<String, Object>();
Set<String> wList = new HashSet<>();
eMap.put("DATA LIST", wList);
假设集合包含['aaa','bbb']; 如何检查地图中是否存在“ aaa”?
谢谢。 :)
答案 0 :(得分:1)
在您的示例中,eMap
的类型为Map<String, List<String>>
。那会容易得多。然后,您必须遍历值以进行检查:
eMap.values().stream().anyMatch(l -> l.contains("aaa"));
以及地图的定义:
Map<String, Set<String>> eMap = new HashMap<>();
答案 1 :(得分:1)
您可以通过以下方式进行检查:
使用Java 8 :
public static boolean checkValueExists(Map<String, Object> eMap, String searchedValue){
return eMap.values().parallelStream()
.flatMap(set -> ((Set<String>)set).stream())
.anyMatch(set -> set.contains(searchedValue));
}
常规方式:
public static boolean checkValueExists(Map<String, Object> eMap, String searchedValue){
for (Map.Entry<String, Object> item : eMap.entrySet()) {
String key = item.getKey();
Set<String> setValue = (Set<String>) item.getValue();
if(setValue.contains(searchedValue)){
return true;
}
}
return false;
}
在这里,您必须熟悉Map<String, Object> eMap
。获得其值为Set<String>
。现在,您必须在setValue
上搜索searchedValue
。
以下是数据集:
Map<String, Object> eMap = new HashMap<>();
Set<String> numberList = new HashSet<>();
numberList.add("Number 1");
numberList.add("Number 2");
numberList.add("Number 3");
eMap.put("Number LIST", numberList);
Set<String> fruitList = new HashSet<>();
fruitList.add("Apple");
fruitList.add("Banana");
fruitList.add("Tomato");
eMap.put("Fruit LIST", fruitList);
String searchedValue="Number 3";
System.out.println("Is Value exists :"+checkValueExists(eMap,searchedValue));
答案 2 :(得分:0)
Map<String, Set<String>> eMap = new HashMap<>();
Set<String> wList = new HashSet<>();
wList.add("aaa");
wList.add("bbb");
eMap.put("DATA LIST", wList);
System.out.println(
eMap.values().parallelStream().flatMap(set -> set.stream()).anyMatch(set -> set.contains("bbb")));
如果要在地图的集合中搜索值,则它的工作原理如下。 您将所有集合平面映射到一个流,然后检查搜索到的值是否存在。
我也建议使用
Map<String, Set<String>>
代替
Map<String, Object>
因为那样您将不需要强制转换(类型安全)
答案 3 :(得分:0)
您可以使用Java 8流api功能。
from itertools import product
n = 4 #number of elements
s = 3 #sum of elements
r = []
for x in range(n):
r.append(x)
result = [p for p in product(r, repeat=n) if sum(p) == s]
print(len(result))
print(result)
然后可以将数据存储在新的地图或列表中,或使用任何方式存储。