问题描述
限时送ChatGPT账号..我有以下 HashMap
,其中 key
是 String
,value
由 value
表示代码>ArrayList:
I have the following HashMap
where the key
is a String
and the value
is represented by an ArrayList
:
HashMap<String, ArrayList<String>> productsMap = AsyncUpload.getFoodMap();
我还有另一个ArrayList
在我的应用程序中实现.
I also have another ArrayList<String> foods
implemented in my application.
我的问题是,找出我的 HashMap
是否包含来自我的第二个 ArrayList
的特定 String
的最佳方法是什么?
My question is, What would be the best way to find out if my HashMap
contains a Specific String
from my second ArrayList
?
我试过没有成功:
Iterator<String> keySetIterator = productsMap.keySet().iterator();
Iterator<ArrayList<String>> valueSetIterator = productsMap.values().iterator();
while(keySetIterator.hasNext() && valueSetIterator.hasNext()){
String key = keySetIterator.next();
if(mArrayList.contains(key)){
System.out.println("Yes! its a " + key);
}
}
推荐答案
为什么不:
// fast-enumerating map's values
for (ArrayList<String> value: productsMap.values()) {
// using ArrayList#contains
System.out.println(value.contains("myString"));
}
如果你必须遍历整个 ArrayList
,而不是只查找一个特定的值:
And if you have to iterate over the whole ArrayList<String>
, instead of looking for one specific value only:
// fast-enumerating food's values ("food" is an ArrayList<String>)
for (String item: foods) {
// fast-enumerating map's values
for (ArrayList<String> value: productsMap.values()) {
// using ArrayList#contains
System.out.println(value.contains(item));
}
}
编辑
过去我用一些 Java 8 习语更新了这个.
Past time I updated this with some Java 8 idioms.
Java 8 流 API 允许以更具声明性(并且可以说是优雅)的方式来处理这些类型的迭代.
The Java 8 streams API allows a more declarative (and arguably elegant) way of handling these types of iteration.
例如,这是实现相同目标的(有点过于冗长)方法:
For instance, here's a (slightly too verbose) way to achieve the same:
// iterate foods
foods
.stream()
// matches any occurrence of...
.anyMatch(
// ... any list matching any occurrence of...
(s) -> productsMap.values().stream().anyMatch(
// ... the list containing the iterated item from foods
(l) -> l.contains(s)
)
)
...这是实现相同目标的更简单方法,最初迭代 productsMap
值而不是 foods
的内容:
... and here's a simpler way to achieve the same, initially iterating the productsMap
values instead of the contents of foods
:
// iterate productsMap values
productsMap
.values()
.stream()
// flattening to all list elements
.flatMap(List::stream)
// matching any occurrence of...
.anyMatch(
// ... an element contained in foods
(s) -> foods.contains(s)
)
这篇关于如何验证HashMap中的值是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论