java:Set,Map排序输出到Writer

一般来说java.util.Set,java.util.Map输出的内容的顺序并不是按key的顺序排列的,但是java.util.TreeMap,java.util.TreeSet的实现却可以让Map/Set中元素内容以key的顺序排序,所以利用这个特性,可以将Map/Set转为TreeMap,TreeSet然后实现排序输出。
以下是实现的代码片段:

    /** * 对{@link Map}中元素以key排序后,每行以{key}={value}形式输出到{@link Writer}
* map为空或null时则不向writer写入任何内容 * @param map * @param writer 为null抛出{@link IllegalArgumentException} * @throws IOException */
public static void storeSortedMap(Map map,Writer writer) throws IOException { if(null==writer) throw new IllegalArgumentException("the arugment 'writer' must not be null "); TreeMap sortedMap = new TreeMap(); if(null!=map) sortedMap.putAll(map); BufferedWriter bw=(writer instanceof BufferedWriter)?(BufferedWriter)writer : new BufferedWriter(writer); for (Entry e:sortedMap.entrySet()) { bw.write(e.getKey() + "=" + e.getValue()); bw.newLine(); } bw.flush(); } /** * 对 {@link Collection}中元素排序后(去除重复),元素分行输出到{@link Writer}
* collection为空或null时则不向writer写入任何内容 * @param collection * @param writer 为null抛出{@link IllegalArgumentException} * @throws IOException */
public static void storeSortedSet(Collection collection,Writer writer) throws IOException { if(null==writer) throw new IllegalArgumentException("the arugment 'writer' must not be null "); TreeSet sortedSet = new TreeSet(); if(null!=collection) sortedSet.addAll(collection); BufferedWriter bw=(writer instanceof BufferedWriter)?(BufferedWriter)writer : new BufferedWriter(writer); for (String e:sortedSet) { bw.write(e); bw.newLine(); } bw.flush(); }

调用示例如下:

Map map;
//....
storeSortedMap(map,new FileWriter(new File("c:\\id.txt")));
Set set;
//....
storeSortedSet(set,new FileWriter(new File("c:\\trainval.txt")));

生成结果已经是排序的了
java:Set,Map排序输出到Writer_第1张图片

java:Set,Map排序输出到Writer_第2张图片

你可能感兴趣的:(java,Map,Set,排序,java)