Home  >  Article  >  Java  >  Sample code sharing of Set and Map sorting output to Writer in Java

Sample code sharing of Set and Map sorting output to Writer in Java

黄舟
黄舟Original
2017-03-24 10:40:531561browse

这篇文章主要介绍了 java中 SetMap排序输出到Writer详解及实例的相关资料,需要的朋友可以参考下

 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}<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 &#39;writer&#39; 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 &#39;writer&#39; 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();
  }

调用示例如下:

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

生成结果已经是排序的了
Sample code sharing of Set and Map sorting output to Writer in Java

Sample code sharing of Set and Map sorting output to Writer in Java

The above is the detailed content of Sample code sharing of Set and Map sorting output to Writer in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn