Shortest way to reverse Properties

后端 未结 3 1482
一生所求
一生所求 2021-01-22 09:05

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

If there are c

相关标签:
3条回答
  • 2021-01-22 10:02

    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

    0 讨论(0)
  • 2021-01-22 10:05

    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);
    }
    
    0 讨论(0)
  • 2021-01-22 10:08

    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.

    0 讨论(0)
提交回复
热议问题