用于CSV文件处理的Java数据类型

时间:2014-02-28 03:03:53

标签: java csv types

我正在解决这个问题,找到一个合适的数据类型,但我不能解决哪个是最有效和简单的方法来编程,而不使用任何第三方库:

问题: 考虑CSV文件中自1990年以来每月给出的N个公司的股价。文件格式如下,第一行为标题。

Year,Month,Company A, Company B,Company C, .............Company N 
1990, Jan, 10, 15, 20, , ..........,50 
1990, Feb, 10, 15, 20, , ..........,50 
. 
. 
. 

。 2013年9月,50日,10日,15日............ 500

输出: 每个公司年度和月份的清单,其中股价最高。

我考虑过使用树,Hashmap,列表,但我无法完成THE ONE解决方案。到目前为止,我是Java的新手,有几周的Java编码经验。任何形式的伪代码,程序或使用什么数据类型的帮助都是值得赞赏的。

2 个答案:

答案 0 :(得分:2)

好的,有无数种方法可以做到这一点,但我最喜欢的方法是创建一个公司类来持有Company.name,Company.month,Company.year,Company.price并使用Map来添加数据。然后,添加逻辑将检查地图以查看是否存在具有相同名称的公司,如果不存在或新公司价格较大,则只需将新公司数据放入具有公司名称作为关键字的地图中。好吧,下面的代码只是为了演示目的,我会使用eclipse生成getters / setter并使用那些代替直接成员变量,就像演示一样。此演示缺少从CSV文件中读取和收集公司数据。

CompanyLoader.java

package org.cnci.poc;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class CompanyLoader {
   private List<Company> companies;
   private int lastReadIdx=0;

   public CompanyLoader() {
   }

   // Simply read the CSV and return the next set of company data
   private Company getNextCompanyData() {
      if (companies == null) {
         lastReadIdx = 0;
         try {
            loadCompanies();
         } catch (Exception e) {
         }
      }
      if (companies == null) return null;
      if (lastReadIdx < companies.size()) return companies.get(lastReadIdx++);
      return null;
   }

   public void loadCompanies() throws Exception {
      Scanner s = null;
      try {
         companies = new ArrayList<Company>();
         File f = new File("test.csv");
         System.out.println(f.getAbsolutePath());
         s = new Scanner(new FileInputStream(f));
         String[] headers = readLine(s);
         System.out.println("headers: " + Arrays.toString(headers));
         if (headers != null && headers.length >0) {
            String[] data = null;
            while ((data = readLine(s)) != null) {
               System.out.println("data: " + Arrays.toString(data));
               if (data.length != headers.length) {
                  companies = null;
                  throw new Exception("Invalid Data - headers count " + headers.length + " does not match with data count "+data.length);
               }
               String year = data[0];
               String month = data[1];
               for (int x=2; x<data.length; x++) {
                  double price = new Double(data[x]).doubleValue();
                  Company company = new Company(headers[x], year, month, price);
                  companies.add(company);
               }
            }
         }
      } finally {
         if (s != null) s.close();
      }
   }

   private String[] readLine(Scanner s) {
      if (s.hasNextLine()) {
         return s.nextLine().trim().split(",");
      }
      return null;
   }

   public void processCompanies() {
      Map<String, Company> companies = new HashMap<String, Company>();
      Company newCompany = null;

      // repeat until all company data processed from CSV file
      while ((newCompany = getNextCompanyData()) != null) {
         Company oldCompany = companies.get(newCompany.getName());
         if (oldCompany == null || newCompany.getPrice() > oldCompany.getPrice())
            companies.put(newCompany.getName(), newCompany);
      }
      // Done, now display the winners
      for (String name : companies.keySet()) {
         Company company = companies.get(name);
         System.out.println(company.getName() + " highest price " + company.getPrice() + " is " + company.getMonth() + " " + company.getYear());
      }
   }

   public static void main(String[] args) {
      CompanyLoader loader = new CompanyLoader();
      loader.processCompanies();
   }
}

Company.java

package org.cnci.poc;

public class Company {
   private String name;
   private String year;
   private String month;
   private double price;

   public Company(String name, String year, String month, double price) {
      super();
      this.name = name;
      this.year = year;
      this.month = month;
      this.price = price;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getYear() {
      return year;
   }
   public void setYear(String year) {
      this.year = year;
   }
   public String getMonth() {
      return month;
   }
   public void setMonth(String month) {
      this.month = month;
   }
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }

   @Override
   public String toString() {
      return "Company [name=" + name + ", year=" + year + ", month=" + month + ", price=" + price + "]";
   }
}

test.csv

Year,Month,Company A,Company B,Company C,Company D,Company N 
1990, Jan, 10, 15, 20, 31, 50 
1990, Feb, 11, 14, 21, 30, 51 

输出:

C:\Projects\Java\POC\test.csv
headers: [Year, Month, Company A,  Company B, Company C,  Company D,  Company N]
data: [1990,  Jan,  10,  15,  20,  31,  50]
data: [1990,  Feb,  11,  14,  21,  30,  51]
Company B highest price 15.0 is  Jan 1990
Company C highest price 21.0 is  Feb 1990
Company N highest price 51.0 is  Feb 1990
Company A highest price 11.0 is  Feb 1990
Company D highest price 31.0 is  Jan 1990

答案 1 :(得分:0)

好吧。你应该把每一行都读成一个字符串。然后,对于标题之后的每一行,您可以遵循以下几种策略之一:创建日期数组,以及每个公司股票价格的浮点数组

或者创建一个公司对象,其本身具有日期和股票价格的数组)

您需要在公司对象中使用“addDatePrice(日期,价格)方法。您可以通过标题csv行中的信息创建正确数量的公司(并将公司对象赋予nam)