2015-07-20 143 views
2

我有一個方法countOcc(),它打印一個列表(如下)。如何將HashMap寫入CSV?

1:00 ==> 1 hits(s) 
2:00 ==> 4 hits(s) 
3:00 ==> 3 hits(s) 
4:00 ==> 6 hits(s) 
5:00 ==> 14 hits(s) 
6:00 ==> 26 hits(s) 
7:00 ==> 16 hits(s) 
8:00 ==> 25 hits(s) 
9:00 ==> 34 hits(s) 
10:00 ==> 39 hits(s) 
11:00 ==> 33 hits(s) 
12:00 ==> 50 hits(s) 
13:00 ==> 49 hits(s) 
14:00 ==> 51 hits(s) 
15:00 ==> 53 hits(s) 
16:00 ==> 40 hits(s) 
17:00 ==> 20 hits(s) 
18:00 ==> 33 hits(s) 
19:00 ==> 26 hits(s) 
20:00 ==> 18 hits(s) 
21:00 ==> 29 hits(s) 
22:00 ==> 7 hits(s) 

方法:

public void countOcc(ArrayList<Integer> list) { 

    String aout = new String(); 
    System.out.println("\n"); 

    Integer[] numbers = list.toArray(new Integer[list.size()]); 

    Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
    for (int i = 0; i < numbers.length; i++) { 
     int key = numbers[i]; 
     if (map.containsKey(key)) { 
      int occurrence = map.get(key); 
      occurrence++; 
      map.put(key, occurrence); 
     } else { 
      map.put(key, 1); 
     } 
    } 

    Iterator iterator = map.keySet().iterator(); 
    while (iterator.hasNext()) { 
     int key = (Integer) iterator.next(); 
     int occurrence = map.get(key); 

     System.out.println(key+":00"+ " ==> " + occurrence + " hits(s)"); 


    }   

} 

我想有它的輸出csv文件:

1:00,2:00,3:00,4:00,5:00,6:00,7:00,8:00,9:00,10:00,11:00,12:00 
1,4,3,6,14,26,16,25,34,39,33,50 

我知道opencsv,但我真的不知道如何使用它與HashMap。

+0

見溶液(http://stackoverflow.com/a/38749527/2685581) – Ajay

回答

0

As this article explains,寫入CSV文件就像寫入文本文件一樣。

public static void write() 
{ 
    StringBuilder out = new StringBuilder(); 
    for (int key : map.keySet()) 
    { 
     out.append(key + ":00,"); 
    } 

    // remove last ',' from line 
    out = new StringBuilder(out.substring(0, out.length() - 1)); 

    for (int occurence : map.values()) 
    { 
     out.append(occurence + ","); 
    } 

    // remove last ',' from line 
    out = new StringBuilder(out.substring(0, out.length() - 1)); 

    try (FileWriter fw = new FileWriter("my.csv")) 
    { 
     writer.append(out.toString()); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
} 
0

惡癖關閉this opencsv tutorial

Map<String, String> values = new HashMap<>(); 
for (String line : lines) { 
    String[] parts = line.split(" "); 
    String time = parts[0]; 
    String value = parts[2]; 
    values.put(time, value); 
} 
StringWriter writer_ = new StringWriter(); 
CSVWriter writer = new CSVWriter(writer_); 
writer.writeNext(values.keySet().toArray()); 
writer.writeNext(values.values().toArray()); 
writer.close(); 
System.out.println(writer_.toString()); 

這使你的輸出。

+0

密鑰集()和值(順序)的方法調用並不能保證是相同的。所以你最終可能會得到與內容行不匹配的標題 - 也不會對你的標題進行排序。 – nutfox

+0

它給了我OP顯示的順序,並且一直如此。 *聳聳肩* – hd1

0

這裏是寫一個CSV文件可以相應地定製的例子:

import java.io.FileWriter; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 


    public class CsvFileWriter { 


    //Delimiter used in CSV file 
    private static final String COMMA_DELIMITER = ","; 
    private static final String NEW_LINE_SEPARATOR = "\n"; 

    //CSV file header 
    private static final String FILE_HEADER = "id,firstName,lastName,gender,age"; 

    public static void writeCsvFile(String fileName) { 

     //Create new students objects 
     Student student1 = new Student(1, "Ahmed", "Mohamed", "M", 25); 
     Student student2 = new Student(2, "Sara", "Said", "F", 23); 
     Student student3 = new Student(3, "Ali", "Hassan", "M", 24); 
     Student student4 = new Student(4, "Sama", "Karim", "F", 20); 
     Student student5 = new Student(5, "Khaled", "Mohamed", "M", 22); 
     Student student6 = new Student(6, "Ghada", "Sarhan", "F", 21); 

     //Create a new list of student objects 
     List students = new ArrayList(); 
     students.add(student1); 
     students.add(student2); 
     students.add(student3); 
     students.add(student4); 
     students.add(student5); 
     students.add(student6); 

     FileWriter fileWriter = null; 

     try { 
      fileWriter = new FileWriter(fileName); 

      //Write the CSV file header 
      fileWriter.append(FILE_HEADER.toString()); 

      //Add a new line separator after the header 
      fileWriter.append(NEW_LINE_SEPARATOR); 

      //Write a new student object list to the CSV file 
      for (Student student : students) { 
       fileWriter.append(String.valueOf(student.getId())); 
       fileWriter.append(COMMA_DELIMITER); 
       fileWriter.append(student.getFirstName()); 
       fileWriter.append(COMMA_DELIMITER); 
       fileWriter.append(student.getLastName()); 
       fileWriter.append(COMMA_DELIMITER); 
       fileWriter.append(student.getGender()); 
       fileWriter.append(COMMA_DELIMITER); 
       fileWriter.append(String.valueOf(student.getAge())); 
       fileWriter.append(NEW_LINE_SEPARATOR); 
      } 



      System.out.println("CSV file was created successfully !!!"); 

     } catch (Exception e) { 
      System.out.println("Error in CsvFileWriter !!!"); 
      e.printStackTrace(); 
     } finally { 

      try { 
       fileWriter.flush(); 
       fileWriter.close(); 
      } catch (IOException e) { 
       System.out.println("Error while flushing/closing fileWriter !!!"); 
       e.printStackTrace(); 
      } 

     } 
    } 
    } 
+0

我不明白你爲什麼要自己寫這個,如果你可以重用一個現有和經過良好測試的框架。另外:你的代碼不應該使用硬編碼的行分隔符 - 你應該使用系統的值 - 否則你的代碼只能在Windows中工作,而不是在例如。 Linux(或其他方式)。 – nutfox

0

你可能需要這樣的:在Stackflow螺紋[這裏]

public static void countOcc(List<Integer> list) { 
     Map<Integer, Integer> map = new HashMap<>(); 
     for (Integer key : list) { 
      if (map.containsKey(key)) { 
       map.put(key, map.get(key) + 1); 
      } else { 
       map.put(key, 1); 
      } 
     } 

     String csv = "d://data.csv"; 
     try (CSVWriter writer = new CSVWriter(new FileWriter(csv))) { 
      String[] keysArray = new String[map.keySet().size()]; 
      String[] valuesArray = new String[map.values().size()]; 
      int counter = 0; 
      for (Entry<Integer, Integer> entry : map.entrySet()) { 
       keysArray[counter] = entry.getKey() + ":00"; 
       valuesArray[counter] = entry.getValue() + ""; 
       counter++; 
      } 
      writer.writeNext(keysArray); 
      writer.writeNext(valuesArray); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    }