0

I am storing the key = "name" and value = "state" in a Hashmap. Now once I get the hashmap with all keys and values I want to iterate the hashmap and have to check whether the state(value) is running or not If the state is not running I want to print the name of that server(which is key in hashmap) Code I am using is

for(int z=0; z<=containsAll.size();z++) {
    if(!containsAll.containsValue("Running")) {
        System.out.println(containsAll.keySet());
    }
}

Here contains all is the name of my Hashmap. Can someone help me in getting the name for which state is not running

1
  • you could iterate over the EntrySet (you get that with containsAll.entrySet()). Then you check the value for the entry and if it fits your criteria you can print the key of the entry. Commented Jul 21, 2020 at 9:10

3 Answers 3

1
if (containsAll != null) {
        containsAll.forEach((k, v) -> {
            if (v != null && !v.contains("Running")) {
                System.out.println(k);
            }
        });
    }

Iterate every key-value pair of the map, and if the value don't contain "Running", print the key.

Sign up to request clarification or add additional context in comments.

Comments

0

you can traverse the map using entrySet()

   Iterator it = containsAll.entrySet().iterator();
   while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        if(!((pair.getValue()).equals("Running")){
              System.out.println(pair.getKey()+" is not running");
        }
        it.remove(); 
    }

Comments

0

I'd make a new class to represent a server and within this class I'd define the state as boolean and the name as string. Furthermore I'd use a list of those Objects to iterate through and do something like this(given, the list is typed List):

...
for(MyServerObject mso : containsAll){
    if(mso.isRunning())
        System.out.println(mso.getName());
}
...

If this is not possible as you get the Map as is from somewhere else try the following (I'm assuming your Map is typed Map<String,String>):

...
Iterator<Map.Entry<String, String>> iterator = containsAll.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, String> entry = iterator.next();
    if("Running".equalsIgnoreCase(entry.getValue())
        System.out.println(entry.getKey() + " is running!");
}
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.