'Can i remove an element while enumerating through a Properties object?

Can i remove an element while enumerating through a Properties object ?



Solution 1:[1]

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.

Solution 2:[2]

PropertiesimplementsMap<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.

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Dolk
Solution 2 Community
Solution 3 Deepak Silver