如何将字符串与哈希映射中的键进行比较

时间:2016-11-13 09:03:34

标签: java arrays hashmap hashtable

我很难将字符串(str)与hashmap中的键进行比较。从下面的代码中可以看出,我有多个键。我正在将str与密钥进行比较,但我无法获得该特定密钥的值。请注意,地图中包含coin

只有在我直接输入字符串时才有效,例如 entry.getKey().getKeyOne().toString().contains("coin")

String str = "coin";
for(Map.Entry<Pair, String> entry : map.entrySet()) {
    if(entry.getKey().getKeyOne().toString().contains(str)||
        entry.getKey().getKeyTwo().toString().contains(str)) {
            entry.getValue();
    }
}

public class Pair {
    private String keyOne;
    private String keyTwo;

    Pair(String one,String two) {
        this.keyOne=one;
        this.keyTwo=two;
    }

    public String getKeyOne() {
        return keyOne;
    }

    public String getKeyTwo() {
       return keyTwo;
    }
}

2 个答案:

答案 0 :(得分:1)

建议:只要您在Pair中使用自己的课程Map必须覆盖equals()覆盖hashCode()

你用字符串文字作为例子,因为&#34;硬币&#34;在string pool中,所有引用相同的字符串。

在这里运行:

public class Pair {

    private String keyOne;
    private String keyTwo;

    Pair(String one, String two) {
        this.keyOne = one;
        this.keyTwo = two;

    }

    public String getKeyOne() {
        return keyOne;
    }

    public String getKeyTwo() {
        return keyTwo;

    }

    public static void main(String[] args) {
        Map<Pair, String> map = new HashMap();
        map.put(new Pair("coin", "5"), "U");
        map.put(new Pair("bill", "100"), "H");
        map.put(new Pair("10", "5coin"), "T");

        String str = new String("coin");
        for (Map.Entry<Pair, String> entry : map.entrySet()) {
            if (entry.getKey().getKeyOne().toString().contains(str)
                    || entry.getKey().getKeyTwo().toString().contains(str)) {
                System.err.println(entry.getValue());
            }
        }
    }
}

答案 1 :(得分:0)

以下是您的简单示例代码 如果只需要一个Hashmap

public void findInkeys(String findkey){
    HashMap<String, Object> map=new HashMap<>();

    //Place your content of MAp Here
    //Start

    //end
    //or you can place your content anywhere else but make sure is is initialized before this


    Set<String> keys=map.keySet();
    boolean isInKeys=false;
    for (String k : keys)
    {
        if(k.equals(findkey))
        {
            isInKeys=true;
        }
    }
    System.out.println(isInKeys);
}

如果您想要任何hashmap

public void findInkeys(HashMap<String,Object> map,String findkey){

    Set<String> keys=map.keySet();
    boolean isInKeys=false;
    for (String k : keys)
    {
        if(k.equals(findkey))
        {
            isInKeys=true;
        }
    }
    System.out.println(isInKeys);
}

如果您有多个要比较的密钥,请使用以下代码

public void findInkeys(HashMap<String, String> map,ArrayList<String> keyList){
    Set<String> keys=map.keySet();
    boolean isInKeys=false;
    for (String k : keys)
    {
        if(keyList.contains(k))
        {
            isInKeys=true;
        }
    }
    System.out.println(isInKeys);
}