The shortest way to undo properties
In Java, I have an object java.util.Properties
and I want to get another one with the same pairs, but the keys converted to values and vice versa.
If there is a collision (i.e. there are two equal values), just choose an arbitrary key as the value.
What's the shortest way to do this?
Feel free to use libraries, collective collections, etc.
Object A Properties
is an object Hashtable
, so you should be able to do something like:
Hashtable<String, String> reversedProps = new Hashtable<String, String>();
for (String key : props.keySet()) {
reversedProps.put(props.get(key), key);
}
Result: 3 lines of code.
This code is untested, but it should give you the idea.
You might consider using google collections BiMap which is essentially a reversible map. This ensures that the keys as well as the values are unique.
Check here . This is the API
Something like:
Properties fowards = new Properties();
fowards.load(new FileInputStream("local.properties"));
Properties backwards = new Properties();
for (String propertyName : fowards.stringPropertyNames())
{
backwards.setProperty(forwards.get(propertyName), propertyName);
}