Can i remove an element while enumerating through a Properties object ?
3 Answers
Properties
implements
Map<Object,Object>
, so you can iterate over the Set.iterator()
of its Map.entrySet()
, and call Iterator.remove()
on certain entries.
Properties prop = new Properties();
prop.put("k1", "foo");
prop.put("k2", "bar");
prop.put("k3", "foo");
prop.put("k4", "bar");
System.out.println(prop); // prints "{k4=bar, k3=foo, k2=bar, k1=foo}"
Iterator<Map.Entry<Object,Object>> iter = prop.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Object,Object> entry = iter.next();
if (entry.getValue().equals("bar")) {
iter.remove();
}
}
System.out.println(prop); // prints "{k3=foo, k1=foo}"
The reason why you want to call remove()
on an iterator()
is because you don't want to cause a ConcurrentModificationException
.
Related questions
Many beginners often question the value of interface
in Java: this is a great example to show just how powerful interface
can be. Properties implements Map<Object,Object>
, so unless documented otherwise, all the things you can do with a Map
, you can do with a Properties
. The information in the above question is directly relevant and directly applicable to your situation.

- 1
- 1

- 376,812
- 128
- 561
- 623
yes, We can remove an element while enumerating the properties elements
Enumeration<String> enu = (Enumeration<String>)p.propertyNames();
while(enu.hasMoreElements()){
String key = enu.nextElement();
String props = p.getProperty(key);
System.out.println(key + "-" + props );
if(key.equals("neice")) p.remove(key);
}

- 27
- 1
- 3
Have you tried? (sorry, didn't pay attention, you've set the beginner flag ;))
Properties is a subclass of HashMap and HashMap offers an iterator, which is in Fact a subclass of AbstractMapIterator. This iterator implements the remove method. So the answer is - yes, if you iterate through the Properties object.

- 113,398
- 19
- 180
- 268
-
Have you tried would have been the right answer :) Just the fact that Properties extends Map does not mean all methods of Map are available on Properties. cf UnsupportedOperationException. In Java it seems to be acceptable to extend but not obey the Liskov Substitution Principle. – Miserable Variable May 28 '10 at 10:00
-
@Hemal, yes, I know. With a good IDE and some experience you can code such a test in less time that it takes to put a question on SO. But he's a beginner and so I 'deleted' this line in my answer. – Andreas Dolk May 28 '10 at 10:06
-
@Andreas_D I didnt get how Properties is a subclass of HashMap. According to java docs https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html it is a subclass of HashTable. Can you explain? – Abhishek saharn Oct 03 '18 at 12:01