这是测试这两种情况的示例方法。在地图的键中搜索项目,并在每个地图条目的列表中搜索项目:
private static void testMapSearch(){
final ArrayList<String> fruitsList = new ArrayList<String>();
fruitsList.addAll(Arrays.asList("Apple", "Banana", "Grapes"));
final ArrayList<String> veggiesList = new ArrayList<String>();
veggiesList.addAll(Arrays.asList("Potato", "Squash", "Beans"));
final Map<String, ArrayList<String>> productsMap = new HashMap<String, ArrayList<String>>();
productsMap.put("fruits", fruitsList);
productsMap.put("veggies", veggiesList);
final ArrayList<String> foodList = new ArrayList<String>();
foodList.addAll(Arrays.asList("Apple", "Squash", "fruits"));
// Check if items from foodList exist in the keyset of productsMap
for(String item : foodList){
if(productsMap.containsKey(item)){
System.out.println("productsMap contains a key named " + item);
} else {
System.out.println("productsMap doesn't contain a key named " + item);
}
}
// Check if items from foodList exits in productsMap's values
for (Map.Entry<String, ArrayList<String>> entry : productsMap.entrySet()){
System.out.println("\nSearching on list values for key " + entry.getKey() + "..");
for(String item : foodList){
if(entry.getValue().contains(item)){
System.out.println("productMap's list under key " + entry.getKey() + " contains item " + item);
} else {
System.out.println("productMap's list under key " + entry.getKey() + " doesn't contain item " + item);
}
}
}
}
结果如下:
productsMap 不包含名为 Apple 的键
productsMap 不包含名为 Squash 的键
productsMap 包含一个名为 fruits 的键
搜索关键水果的列表值..
productMap 的 key fruits 下的列表包含 Apple 项
productMap 的 key fruits 下的列表不包含 item Squash
productMap 的 key fruits 下的列表不包含 item fruits
搜索关键蔬菜的列表值..
productMap 在 key veggies 下的列表不包含 Apple 项
productMap 在 key veggies 下的列表包含项目 Squash
productMap 在 key veggies 下的列表不包含项目 fruits