【问题标题】:compare java hash map key with the string将java哈希映射键与字符串进行比较
【发布时间】:2019-05-31 06:05:07
【问题描述】:

我想比较一个字符串和一个 hashmap 的键值。

private Map<String, Integer> map1= new HashMap<>();
 map1.put("User1" , 100);
 map1.put("User2" , 200);
 map1.put("User3" , 300);

public void test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equals(user)) {
          System.out.println("yes");    
        }else{
          System.out.println("no"); 
        }
    }
}

但我的代码无法正常工作,即使用户在地图中,我也得到答案,不知道问题出在哪里?

我稍微更改了代码,但给出的答案仍然是否:


import java.util.*;

public class A1 {

 private static Map<String, Integer> map1= new HashMap<>();


 public static boolean test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equalsIgnoreCase(user)) {
          return true;  
        }
    }
    return false;
}

    public static void main(String[] args) {
        map1.put("User1" , 100);
        map1.put("User2" , 200);
        map1.put("User3" , 300);
        if(test("User1" , 100)){
                  System.out.println("yes");    
        }else{
          System.out.println("no"); 
        }
    }
}

@杰森泰

map1.containsKey(user)

工作。

【问题讨论】:

  • 您在哪里向地图添加条目?
  • 一个更简单(更快)的替代方法是使用map1.containsKey(user)
  • 它不在我的代码中,但它在我的原始代码中,我认为我的 if 条件有问题。
  • 地图邮政编码添加了什么数据
  • 请明确说明“不工作”是什么意思

标签: java hashmap


【解决方案1】:
public static boolean test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equalsIgnoreCase(user)) {
          return true;  
        }else{
          return false;
        }
    }
    return false;

此循环总是在第一次迭代时返回,因此只有在第一个键匹配时才会返回 true。

同理:

Iterator<String> it = map1.keySet().iterator();
return it.hasNext() && it.next().equalsIgnoreCase(user);

如果您想继续搜索直到找到匹配的键,请删除循环内的 return false;。

【讨论】:

    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    相关资源
    最近更新 更多