我的HashMap类型包含
String storeId = "3501";
HashMap<String,String> hMap = new HashMap<>();
hMap.put("01",105);
hMap.put("02",3501);
hMap.put("07",3501);
for (int mainLoop=0; mainLoop < 3 ;mainLoop++){
for (Map.Entry<String, String> map : hMap.entrySet()) {
if (storeId.equalsIgnoreCase(map.getValue())) {
fulFillmentType = map.getKey();
}
}
}
每次执行mainLopp。当它第一次达到“ 3501”时,仅应返回“ 02”,而在第三次循环中达到“ 3501”则应返回“ 07”。当前输出仅为“ 07”
答案 0 :(得分:0)
我建议问题是您没有跟踪所有匹配键的状态。如果要跟踪所有匹配的键,请考虑使用字符串集合:
String storeId = "3501";
HashMap<String,String> hMap = new HashMap<>();
hMap.put("01", "105");
hMap.put("02", "3501");
hMap.put("07", "3501");
List<String> matches = new ArrayList<>();
for (int mainLoop=0; mainLoop < 3 ;mainLoop++) {
for (Map.Entry<String, String> map : hMap.entrySet()) {
if (storeId.equalsIgnoreCase(map.getValue())) {
matches.add(map.getKey());
}
}
}
matches.forEach(System.out::println);
请注意,在您最初的问题中,hMap
的值是整数文字,而不是字符串。它们必须是用双引号引起来的字符串,以便代码甚至可以编译。
答案 1 :(得分:0)
您说
应该返回“ 02”
第三循环应返回“ 07”
但是实际上您永远不会“返回”也不会中断任何循环。因此,第一次找到3501时,将{02}分配给fulFillmentType
,第二次将其替换为“ 07”。
因此,在所有迭代之后:fulFillmentType == "07"
现在,您必须知道HashMap
及其entrySet
在读取其内容时不保证任何排序顺序。因此,最后读取的值可以随机为“ 02”或“ 07”
答案 2 :(得分:0)
因为您的这段代码:
hMap.put("02",3501);
hMap.put("07",3501);
如果他们同时行动,他们会发生冲突 他们将结果发送为02或07 但它们的条件与其他条件不同
答案 3 :(得分:0)
您给定的值与键-02和07匹配
因此,我认为我们不需要制作列表或任何内容,我认为这是一种非常简单的逻辑,可以对具有相同值的压缩进行
String storeId = "3501";
HashMap<String, String> hMap = new HashMap<>();
hMap.put("01", "105");
hMap.put("02", "3501");
hMap.put("07", "3501");
for (Map.Entry<String, String> map : hMap.entrySet()) {
if (storeId.equalsIgnoreCase(map.getValue())) {
System.out.println("Match Found with Key " + map.getKey());
}
}
答案 4 :(得分:0)
要从首次匹配中获得结果,您必须break;
循环。如果要获取具有相同值的键,则需要将结果记入new ArrayList<String>()
中。
使用Java 8:
List<String> result = map.entrySet().stream().filter(entry -> "someString".equals(entry.getValue())).map(
Map.Entry::getValue).collect(Collectors.toList());