Java: how would I remove the HashTable entries containing specific value?

Hello Experts,

For the example code below, how would I remove the Key/Value pairs for those entries containing the value "none"?

Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
		hash.put(1, "value1");
		hash.put(2, "none");
		hash.put(3, "value3");
		hash.put(4, "none");
		Enumeration<Integer> e = hash.keys();
	    Object obj;
	    while (e.hasMoreElements()) {
	      obj = e.nextElement();
	      System.out.println(obj + ": " + hash.get(obj));
	    }

Open in new window


In advance, thank you for any suggestions/help...
epifanio67Asked:
Who is Participating?
 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
Use .entrySet() rather than .keys() method of HashTable

Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
		hash.put(1, "value1");
		hash.put(2, "none");
		hash.put(3, "value3");
		hash.put(4, "none");
		
                Iterator<Map.Entry<Integer, String>> e = hash.entrySet().iterator();
	        Map.Entry<Integer, String> entry;
	        while (e.hasNext()) {
	           entry = e.next();
	           System.out.println(entry.getKey() + ": " + entry.getValue());
                   if (entry.getValue().equals("none")) {
                       e.remove();
                   }
	        }

Open in new window

0
 
CEHJConnect With a Mentor Commented:
Don't forget that Hashtable is a legacy class and should be avoided in favour of HashMap, especially if synchronization is not required and if you might need to have null values.
0
 
epifanio67Author Commented:
Thank you experts...
I really appreciate all of your help...

Regards,
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
krakatoaCommented:
You could also do this :

Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
		hash.put(1, "value1");
		hash.put(2, "none");
		hash.put(3, "value3");
		hash.put(4, "none");
	       
	        for(Map.Entry<Integer, String> entry : hash.entrySet()) {
	             
                   if (entry.getValue().equals("none")) {
                       hash.remove(entry);
		System.out.println(entry.getKey() + ": " + entry.getValue()+" was removed");
                   }
	   else{System.out.println(entry.getKey() + ": " + entry.getValue()+" was not removed");}
	        }

Open in new window


... which dispenses with an explicit Iterator.
0
 
krakatoaCommented:
It's a good thing my post came after the question was closed, because, although the code works, it's wrong, so don't use it.
0
 
epifanio67Author Commented:
Thank you for your help though...
I appreciate it...
Regards,
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.