views:

169

answers:

3

I java a java.util.Properties object and I want to obtain another one with the same pairs but keys are converted to values and viceversa.

If there are collision (i.e. there are two equal values) then just pick as value an arbitrary key.

What is the shortest way to do it.

Feel free to use libraries, commons-collections, or whatever.

+2  A: 

A Properties object is a Hashtable object, 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.

Thomas Owens
`putAll` takes a `Map` as its argument, not two collections. For it to work, you need a "reversed" `Map`.
gustafc
Also, it's Hashtable, not HashTable.
job
Removed the `putAll` solution - totally dropped the ball on that one. Also corrected the HashTable/Hashtable mistake.
Thomas Owens
A: 

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);
}
Nick Holt
Can you use fowards.propertyNames() in the for-each loop like that? I've always created an object outside the for-each loop and done it that way. If you can, I can also remove a line of code from my example.
Thomas Owens
@Thomas: yes, the `for` loop gets the `Iterable` object before it starts iterating.
Nick Holt
`propertyNames` returns an `Enumeration<?>`, not an `Iterable<String>`, and so cannot be iterated over with the foreach construct. `stringPropertyNames`, though, returns a `Set<String>` and can be foreached.
gustafc
@gustafc: ooops, thanks for the pointer :-)
Nick Holt
+6  A: 

You can consider using a BiMap by google collections which is essentially a reversable Map. It guarantees uniquness of keys as well as values.

Check it out here. This is the API

Savvas Dalkitsis
This would indeed work, since Java's `Hashtable` class implements the `Map` interface, you can create a new BiMap and then use the `putAll()` method to load the `Properties` object into the BiMap.
Thomas Owens