2017-07-28 59 views
0

有沒有一種方法來排序在java中的屬性對象?排序在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);