Link to home
Start Free TrialLog in
Avatar of GAUTAM
GAUTAMFlag for United States of America

asked on

Creating a csv file from a map

Hi Experts...
I have a map of the type LinkedHashMap<String,Integer>  containing the students name and their marks as String and int data.
How do i create a csv file with the students name and their marks displayed one below the other with the header being two columns as Student and Marks.
Please help...
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

For something simple like this you can 'roll your own' but otherwise use a proper csv writer. Try something like
PrintWriter out = new PrintWriter(new FileWriter("students.csv"));
final String SEP = System.getProperty("line.separator");
out.printf("%s,%s%s", "Student", "Mark", SEP);
Set<Map.Entry<String, Integer>> marks = map.entrySet();
for(Map.Entry<String, Integer> e : marks) {
   out.printf("%s,%s%s", e.getKey(), e.getValue().toString, SEP);
}
out.close();

Open in new window

HahsMap<String, Integer> map = new HashMpa<Strng, Integer)();
map.add("Browm",5);
map.add("Jones",4);

PrintWriter out = new PrintWriter(new FileWriter("marks.csv"));
out.println("Students, Marks";
for(String s : map.keySet()){
out.println(s + "," + map.get(s));

}
out.close();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GAUTAM

ASKER

@for_yan & @CEHJ:Thanks a lot for you replies.
Avatar of GAUTAM

ASKER

@for_yan & @CEHJ:Thanks a lot for your replies.
You are always welcome.
:)