How do you view the map?

I have a map:

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

and I would like to know how to search on it and find something matching a specific line. And if it's a coincidence store, it turns into an arraylist. The map contains the following lines:

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

and the matching line will be 5.

So, 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);
        }

     }
+3
source share
4 answers

Apparently you are trying to find in the 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);
        }
    }

See also the nullif statement.

+2
source

Not quite sure if you understand you, but I think you're looking containsKey?

ht.containsKey("5");
+5
source

, .

:

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

, , .

+3

The map API does not recommend you use Enumeration anymore as your pretty old interface and is expected to be replaced by COllection, but the legacy is still a concern.

The KeySet method returns you a Set Back, and you can directly use the set method to compare

+1
source

Source: https://habr.com/ru/post/1742480/


All Articles