java中 Set与Map排序输出到Writer详解及实例

时间:2021-11-30 23:46:47

 java中 Set与Map排序输出到Writer详解及实例

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

?
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
/**
  * 对{@link Map}中元素以key排序后,每行以{key}={value}形式输出到{@link Writer}<br>
  * map为空或null时则不向writer写入任何内容
  * @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();
 }
 /**
  * 对 {@link Collection}中元素排序后(去除重复),元素分行输出到{@link Writer}<br>
  * collection为空或null时则不向writer写入任何内容
  * @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();
 }

调用示例如下:

?
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")));

生成结果已经是排序的了

java中 Set与Map排序输出到Writer详解及实例

java中 Set与Map排序输出到Writer详解及实例

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!