有没有办法在java中对Properties对象进行排序?
我有字符串对属性进行分组,并检查数据是否以地图格式可用。
请使用此示例:
来自链接: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();
}
}
您可以找到一个没有对属性进行子类化并使用Java 8/9/10的示例
通过这种方式,来自Properties的keySet,keys和entrySet方法返回排序键。然后方法存储也保存已排序的属性文件。
这段代码是here
Properties properties = new Properties() {
private static final long serialVersionUID = 1L;
@Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
Set<Map.Entry<Object, Object>> set1 = super.entrySet();
Set<Map.Entry<Object, Object>> set2 = new LinkedHashSet<Map.Entry<Object, Object>>(set1.size());
Iterator<Map.Entry<Object, Object>> iterator = set1.stream().sorted(new Comparator<Map.Entry<Object, Object>>() {
@Override
public int compare(java.util.Map.Entry<Object, Object> o1, java.util.Map.Entry<Object, Object> o2) {
return o1.getKey().toString().compareTo(o2.getKey().toString());
}
}).iterator();
while (iterator.hasNext())
set2.add(iterator.next());
return set2;
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
考虑到TreeMap是一个有序的Map,那么你可以这样做:
//properties as they are:
System.out.println(System.getProperties());
//now sorted:
TreeMap<Object, Object> sorted = new TreeMap<>(System.getProperties());
System.out.println(sorted);