Search code examples
javacsvdata-structurestreemap

how to write a Treemap as a csv


Currently I am having a tree map which is like

    TreeMap<String, String> tree_map = new TreeMap<String, String>(); 

I then add key and value pairs for the Treemap and now I want to write them in a csv by order and line by line (each key value pair).So I tried with

ArrayList <String> list=new ArrayList<String>();
     for ( String key :tree_map.keySet() ) {

                list.add(key+","+tree_map.get(key).toString());

                  }    

                BufferedWriter br = new BufferedWriter(new FileWriter("C:\\Users\\"));

                for (String element : list) {
                    br.write(element);
                }
                br.close();

But I encountered two problems:

  1. It does not print in order.
  2. I want to print each key ,value pair line by line

Any help is appreciated.


Solution

  • I used opencsv library and this apparently made the trick.Hope it helps anyone.

    CSVWriter writer = new CSVWriter(new FileWriter("C:\\Users\\map.csv")) ;
                for(String keys:tree_map.keySet()){
                    String[] y=new String[2];
                    y[0]=keys;
                    y[1]=tree_map.get(keys).toString();
                    writer.writeNext(y);
                }