2017-07-28 9 views
0

javaでPropertiesオブジェクトをソートする方法はありますか?Javaでプロパティをソートする

プロパティをグループ化する文字列があり、データがマップ形式で使用できるかどうかがチェックされます。

+1

は 'のTreeMap <文字列を作成します。 、String> '、あなたのプロパティでそれを記入し、新しい' Properties'を作成し、マップからそれを記入してください... –

+1

なぜあなたは並べ替えが必要でしょうか? – Lino

+1

@ UsagiMiyamoto新しい「プロパティ」を作成すると、ソート順が失われます。 – EJP

答えて

0

この例を使用してください:

リンクから:http://www.java2s.com/Tutorial/Java/0140__Collections/SortPropertieswhensaving.htm

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

} 
-1

は、あなたが行うことができ、TreeMapのは、ソートされた地図であることを考えてみましょう:

//properties as they are: 
System.out.println(System.getProperties()); 

//now sorted: 
TreeMap<Object, Object> sorted = new TreeMap<>(System.getProperties()); 
System.out.println(sorted); 
関連する問題