2013-04-30 74 views
-2

我正在製作一個程序來讀取excel文件中的數據並將它們存儲在表中。但是因爲我是Java新手,所以在編寫其中一個時遇到了困難。這是我的問題,我已經設法從excel文件中讀取所有數據作爲字符串並將它們存儲在一個表中。但我的項目是通過升序ID將它們存儲在表格中。有人可以幫助我創建一個比較器來比較LinkedHashmaps並通過它們的ID存儲它們嗎? ,我要存儲的數據是像下面:LinkedHashMap的比較器

ID Name Salary   
50 christine 2349000   
43 paulina 1245874   
54 laura 4587894 

用於分析數據的代碼是以下:

private static LinkedHashMap parseExcelColumnTitles(List sheetData) { 

    List list = (List) sheetData.get(0); 
    LinkedHashMap < String, Integer > tableFields = new LinkedHashMap(list.size()); 
    for (int j = 0; j < list.size(); j++) { 
     Cell cell = (Cell) list.get(j); 
     tableFields.put(cell.getStringCellValue(), cell.getCellType()); 
    } 

    return tableFields; 

} 

private static LinkedHashMap[] parseExcelColumnData(List sheetData) { 

    LinkedHashMap[] tousRows = new LinkedHashMap[sheetData.size() - 1]; 
    for (int rowCounter = 1; rowCounter < sheetData.size(); rowCounter++) { 

     List list = (List) sheetData.get(rowCounter); 

     LinkedHashMap < String, Integer > tableFields = new LinkedHashMap(list.size()); 
     String str; 
     String[] tousFields = new String[list.size()]; 

     int i = 0; 

     for (int j = 0; j < list.size(); j++) { 
      Cell cell = (Cell) list.get(j); 
      if (cell != null) { 
       if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { 
        tableFields.put(String.valueOf(cell 
         .getNumericCellValue()), cell.getCellType()); 
       } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { 
        tableFields.put(cell.getStringCellValue(), cell 
         .getCellType()); 
       } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { 
        tableFields.put(String.valueOf(cell 
         .getBooleanCellValue()), cell.getCellType()); 
       } 
      } 

     } 
     tousRows[rowCounter - 1] = tableFields; 
    } 

    return tousRows; 

} 
+0

什麼是(鍵,值)對你的地圖? – NINCOMPOOP 2013-04-30 07:12:34

回答

1

可以使用TreeMap代替LinkedHashMap,因爲你不想保留插入的順序,並且對於排序TreeMap是更好的選擇。 閱讀本太Java TreeMap Comparator

1

你可以做這樣的模式:

public class Salary implements Comparable<Salary> { 
    private Long id; 
    private String name; 
    private Double salary; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public Double getSalary() { 
     return salary; 
    } 

    public void setSalary(Double salary) { 
     this.salary = salary; 
    } 

    @Override 
    public int compareTo(Salary o) { 
     if (o.getId() < this.id) { 
      return -1; 
     } else if (o.getId() > this.id) { 
      return 1; 
     } 
     return 0; 
    } 
} 

然後你可以使用Collections.sort(list)訂購您LinkedHashMap