我有一个树形图,它有已排序的信息(我按照hashmap的值排序,而不是键)但是当我想将它们写入属性文件时,顺序不是序列。有什么问题?任何人都可以帮助我吗?
ArrayList<Integer> values = new ArrayList<Integer>();
values.addAll(wordcount.values());
Collections.sort(values, Collections.reverseOrder());
ValueComparator bvc = new ValueComparator(wordcount);
TreeMap<String, Integer> sorted_map = new TreeMap(bvc);
sorted_map.putAll(wordcount);
Properties props=new Properties();
FileInputStream fis=new FileInputStream("abc.properties");
props.load(fis);
for (Integer i : values) {
for (String s : sorted_map.keySet()) {
if (sorted_map.get(s) == i){
props.setProperty(s, String.valueOf(i));
props.store(new FileOutputStream("abc.properties"), null);
break;
}
}
}
答案 0 :(得分:3)
这是属性的扩展,它将通过store()为您提供排序的键,条目,toString()输出和文件输出:
import java.util.*;
/**
* Extension of Properties with sorted keys for alphabetic output.
* Neither optimized for performance nor thread-safety.
*/
public class SortedProperties extends Properties {
/**
* Called throughout by Properties, including
* Properties.store(OutputStream out, String comments).
*/
@Override
public synchronized Enumeration<Object> keys() {
return new Vector(this.keySet()).elements();
}
/**
* Called by Properties.stringPropertyNames() and this.keys().
*/
@Override
public Set<Object> keySet() {
Set<Object> keySet = super.keySet();
if(keySet==null) return keySet;
return new TreeSet(keySet);
}
/**
* Called by Properties.toString().
*/
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
Set<Map.Entry<Object, Object>> entrySet = super.entrySet();
if (entrySet==null) return entrySet;
Set<Map.Entry<Object, Object>> sortedSet = new TreeSet(new EntryComparator());
sortedSet.addAll(entrySet);
return sortedSet;
}
/**
* Comparator for sorting Map.Entry by key
* Assumes non-null entries.
*/
class EntryComparator implements Comparator<Map.Entry<Object, Object>> {
@Override
public int compare(Map.Entry<Object, Object> entry1, Map.Entry<Object, Object> entry2) {
return entry1.getKey().toString().compareTo(entry2.getKey().toString());
}
}
}
答案 1 :(得分:2)
如果使用java.util.Properties,则键值对存储在Hashmap中,无论您如何在HashMap中插入已排序的值,都不会维护任何顺序。
将它们写入文件中以保持排序的唯一方法是自己实现输出。
答案 2 :(得分:0)
根据定义,TreeMap按其键排序。您可以在键之间创建新的比较功能,但您必须根据需要交换键和值的角色。设K和V为键和值的类型。
TreeMap<V,K> tree = new TreeMap<V,K>()
for (Entry<K,V> entry : yourHashMap.entrySet())
tree.put(entry.getValue(), entry.getKey()); // note swap
for (Entry<V,K> entry : tree.entrySet())
properties.add(...)