我有一个 hashmap,它的键是字符串,值存储为列表。
Map<String,List<Integer>> posmap = new HashMap<>();
因为我在同一个键下有多个值。 因此,例如我有 4 个键,值是:
[1681, 3523]
[276, 489]
[1527, 2865]
[300]
我还有另一个 treeList,其中包含这些已排序的值。我想做的是(并询问);
Iterator<Integer> itr=myTreeSet.iterator();
while(itr.hasNext())
{
int check = itr.next();
for(Object value : map2.entrySet())
{
//System.out.println("Value is :" + value);
}
}
我想用我的 Hashmap entrySet 检查 itr,如代码所示,如果等于则返回 hashmap 键。以上代码将 entrySet 作为数组返回。简述如何查看itr属于hashmap的entrySet,属于哪个key。
我将 map1 和 map2 作为参数
static void game(Map map1, Map map2, Hero h, HashSet< Integer> hash)
对不起各位。我没说清楚,我想你很困惑。我首先在主函数中定义这个映射:
Map<String, Enemy> enemymap = new HashMap<>();
Map<String,List<Integer>> posmap = new HashMap<>();
我也将它们填充到 main func 中。填充它们后,我将它们发送到我有问题的功能游戏。 posmap是map2。所以我指向posmap。抱歉造成混淆。 完整的函数代码。
static void game(Map map1, Map map2, Hero h, HashSet< Integer> hash)
{
TreeSet<Integer> myTreeSet = new TreeSet<>(); // For sorting min to max-for alignment
myTreeSet.addAll(myHashset);
System.out.println(myTreeSet);
String start = "Micheal started travel with" + " " + h.getHealth() + " " + "HP!";
Iterator<Integer> itr=myTreeSet.iterator();
while(itr.hasNext())
{
int check = itr.next();
/* for(Map.Entry<String, List<Integer>> entry : map2.entrySet())
{
if(entry.getValue() != null && entry.getValue().contains(check))
System.out.println("The key " + entry.getKey() + "contains the treeset value " + check);
} -/
}
}
从主函数发送为:
game(enemymap, posmap , hero, myHashset);
最佳答案
其他解决方案打印或返回单个 key 。根据您最初的简短帖子,我认为您想要一套,所以这就是我制作的。
根据@ajb 的建议编辑:
Set<Integer> myTreeSet = new TreeSet<>();
Map<String,List<Integer>> posmap = new HashMap<>();
Iterator<Integer> itr = myTreeSet.iterator();
//The set of keys containing values in any list of posmap
Set<String> matchedKeys = new HashSet<>();
//Iterate through the TreeSet Integers
itr.forEachRemaining(itrVal -> {
//Stream each entry of the posmap
posmap.entrySet().stream()
//Remove the entries without the itrVal in the entry's list
.filter(entry -> entry.getValue().contains(itrVal))
//Add each key with a match to the set
.forEach(matchedEntry -> matchedKeys.add(matchedEntry.getKey()));
});
return matchedKeys;
如果您可以随意使用 Apache Commons,这可能是一个不错的方法:
Set<Integer> myTreeSet = new TreeSet<>();
Map<String,List<Integer>> posmap = new HashMap<>();
Iterator<Integer> itr = myTreeSet.iterator();
Set<String> matchedKeys = new HashSet<>();
List<Integer> treeSetValues = IteratorUtils.toList(itr);
treeSetValues.stream().map(val -> {
return posmap.entrySet().stream()
.filter(entry -> entry.getValue().contains(itrVal))
.collect(Collectors.toSet());
});
return matchedKeys;
如果您不能使用 IteratorUtils.toList(),您可以使用 Guava 和 Lists.newArrayList()。
关于java - 比较存储为 List 结构的 Hashmap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42334599/