如何在java中对属性进行排序?

新手上路,请多包涵

我有一个 Properties 对象,有时我需要添加其他 Properties 到它。

 Properties myBasicProps = this.getClass.getResourceAsStream(MY_PROPS_PATH);
...
Properties otherProps = new Properties();
otherProps.load(new StringReader(tempPropsString)); //tempPropsString contains my temporary properties
myBasicProps.putAll(otherProps);

我想在此之后排序 myBasicProps 。我不想获取所有键和值,用 Collections.sort() 对它们进行排序,然后将它们全部放入一个新对象。有没有更好的办法?

原文由 shift66 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 556
2 个回答

不, java.util.Properties 扩展 java.util.Hashtable 没有为键或值定义可预测的排序顺序。

您可以尝试将所有值转储到 java.util.TreeMap 类的内容中,这将对您的键施加自然排序。

原文由 harto 发布,翻译遵循 CC BY-SA 3.0 许可协议

您所要做的就是创建扩展属性的类。资料来源: java2s.com

 import java.io.FileOutputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

public class Main{
  public static void main(String[] args) throws Exception {
    SortedProperties sp = new SortedProperties();
    sp.put("B", "value B");
    sp.put("C", "value C");
    sp.put("A", "value A");
    sp.put("D", "value D");
    FileOutputStream fos = new FileOutputStream("sp.props");
    sp.store(fos, "sorted props");
  }

}
class SortedProperties extends Properties {
  public Enumeration keys() {
     Enumeration keysEnum = super.keys();
     Vector<String> keyList = new Vector<String>();
     while(keysEnum.hasMoreElements()){
       keyList.add((String)keysEnum.nextElement());
     }
     Collections.sort(keyList);
     return keyList.elements();
  }

}

这个对我有用。

原文由 danisupr4 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题