簡體   English   中英

來自CSV的Java Hashmap

[英]Java Hashmap from csv

我試圖在一個類中使用HAshmap,以便從其他類中查找給出產品代碼的產品描述。 雖然二傳手(填充)似乎一切正常,但是當我嘗試使用getter(getdesc)時,我得到了一個錯誤。

我正在使用的csv文件只有2個filds(cod,des)。 稍后,我計划從JDBC SQL服務器源填充哈希圖。

我可能使用了錯誤的語法。 如果有人可以提供幫助,我將不勝感激。

那是我當前的班級代碼:

package bookRecommender;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;



public class ProdutoDescricao


{

        public static void main(String[] args) {}

    @SuppressWarnings({ "resource", "unused" })
    public static void populate(String[] args) throws IOException {
        Map<String, ArrayList<String>> produtos=null;
        try { 

               String csvFile = "Data/produto_descricao.csv";


               BufferedReader br = new BufferedReader(new FileReader(csvFile));
               String line = "";
               StringTokenizer st = null;

               produtos= new HashMap<String, ArrayList<String>>();

               int lineNumber = 0; 
               int tokenNumber = 0;

                           while ((line = br.readLine()) != null) {
               lineNumber++;



                st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                tokenNumber++;


                            String token_lhs=st.nextToken();
                            String token_rhs= st.nextToken();


                            ArrayList<String> arrVal = produtos.get(token_lhs);
                            if (arrVal == null) {
                                arrVal = new ArrayList<String>();
                                produtos.put(token_lhs,arrVal);
                            }
                            arrVal.add(token_rhs);                            

                            }
                        }

                        System.out.println("Final Hashmap is : "+produtos);




} catch (Exception e) {
               System.err.println("CSV file cannot be read : " + e);
             }

    }

  public  String getdesc (long cod)  
  {

    return produto.get(cod);
//Here is the sysntax error
  }

}

produtos= new HashMap<String, ArrayList<String>>() produtos它沒有值,為空。

ArrayList<String> arrVal = produtos.get(token_lhs); 此行有問題,您必須首先在地圖中添加值,然后獲取這些值。

您有一個具有String鍵和ArrayList值類型的映射,但是您嘗試檢索具有long key和String值類型的值。

 public  ArrayList<String> getdesc (String cod)  
  {
    return produtos.get(cod);
  }

還聲明字段“ produtos”:

 private static Map<String, ArrayList<String>> produtos;

完整的課程代碼: http : //pastebin.com/QLZryqT8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM