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.

+2


source to share


3 answers


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.

+2


source


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

+6


source


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

      

+1


source







All Articles