java中 Set與Map排序輸出到Writer詳解及實(shí)例
一般來說java.util.Set,java.util.Map輸出的內(nèi)容的順序并不是按key的順序排列的,但是java.util.TreeMap,java.util.TreeSet的實(shí)現(xiàn)卻可以讓Map/Set中元素內(nèi)容以key的順序排序,所以利用這個(gè)特性,可以將Map/Set轉(zhuǎn)為TreeMap,TreeSet然后實(shí)現(xiàn)排序輸出。
以下是實(shí)現(xiàn)的代碼片段:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * 對(duì){@link Map}中元素以key排序后,每行以{key}={value}形式輸出到{@link Writer}<br> * map為空或null時(shí)則不向writer寫入任何內(nèi)容 * @param map * @param writer 為null拋出{@link IllegalArgumentException} * @throws IOException */ public static void storeSortedMap(Map<String,String> map,Writer writer) throws IOException { if ( null ==writer) throw new IllegalArgumentException( "the arugment 'writer' must not be null " ); TreeMap<String, String> sortedMap = new TreeMap<String,String>(); if ( null !=map) sortedMap.putAll(map); BufferedWriter bw=(writer instanceof BufferedWriter)?(BufferedWriter)writer : new BufferedWriter(writer); for (Entry<String,String> e:sortedMap.entrySet()) { bw.write(e.getKey() + "=" + e.getValue()); bw.newLine(); } bw.flush(); } /** * 對(duì) {@link Collection}中元素排序后(去除重復(fù)),元素分行輸出到{@link Writer}<br> * collection為空或null時(shí)則不向writer寫入任何內(nèi)容 * @param collection * @param writer 為null拋出{@link IllegalArgumentException} * @throws IOException */ public static void storeSortedSet(Collection<String> collection,Writer writer) throws IOException { if ( null ==writer) throw new IllegalArgumentException( "the arugment 'writer' must not be null " ); TreeSet<String> sortedSet = new TreeSet<String>(); 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(); } |
調(diào)用示例如下:
1
2
3
4
5
6
|
Map<String,String> map; //.... storeSortedMap(map, new FileWriter( new File( "c:\\id.txt" ))); Set<String,String> set; //.... storeSortedSet(set, new FileWriter( new File( "c:\\trainval.txt" ))); |
生成結(jié)果已經(jīng)是排序的了
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!