开发者

How do you search through a map?

I have a map:

Map<String, String> ht = new HashMap();

and I would like to know how to search through it and find anything matching a particular string. And if it is a match store it into an arraylist. The map contains strings like this:

开发者_Go百科

1,2,3,4,5,5,5

and the matching string would be 5.

So for I have this:

  String match = "5";
  ArrayList<String> result = new ArrayList<String>();

 Enumeration num= ht.keys();
     while (num.hasMoreElements()) {
        String number = (String) num.nextElement();

        if(number.equals(match))
        {
           result.add(number);
        }

     }


Not quite sure if I understand you, but I guess you are looking for containsKey?

ht.containsKey("5");


I am guessing you want to find keys from values.

Simple code:

List<String> matches = new ArrayList<String>();
for (Map.Entry<String,String> entry : map.keys()) {
    if (targetValue.equals(entry.getValue())) {
        matches.add(entry.getKey());
    }
}

Better perhaps would be to use a second map for the reverse mapping, or a bidirectional map from a third-party library.


Apparently you are trying to find in values. So here is something that would work:

Map<String, String> m = new HashMap<String, String>();
..

List<String> result = new ArrayList<String>();
    for(String s: m.values()){
        if(s.equals("5")){
            result.add(s);
        }
    }

Also, watch for nulls in your if statement.


Map API does not encourage you to use Enumeration any more as its a pretty old interface and was expected to be replaced by COllection interfaces, but legacy is still a concern.

KeySet method returns you a Set back and you can directly use contains method of set for the comparison

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜