Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将内容放入hashmap中_Java_Hashmap - Fatal编程技术网

Java 如何将内容放入hashmap中

Java 如何将内容放入hashmap中,java,hashmap,Java,Hashmap,我在CSV文件中有这样的内容 User1,What is your favorite color?,color User1,What is the name of your pet?,pet User1,What is your mother's maiden name?,mother User2,In what city were you born?,city User2,What elementary school did you attend?,school User2,What was

我在CSV文件中有这样的内容

User1,What is your favorite color?,color
User1,What is the name of your pet?,pet
User1,What is your mother's maiden name?,mother
User2,In what city were you born?,city
User2,What elementary school did you attend?,school
User2,What was your first best friend's name?,friend
我需要调用OIMAPI,它将采用如下参数

void setUserChallengeValues(java.lang.String userID,
                        boolean isUserLogin,
                        java.util.HashMap quesAnsMap)
其中quesAnsMap参数表示质询问题和答案的HashMap

用userid的hashmap作为键,问答作为值,解析CSV文件的有效方法是什么

我的hashmap应该像User1是键,value应该有疑问作为键,答案作为值

有没有要参考的示例代码段


谢谢

使用
String.split()

HashMap userAnswers=newhashmap();
BufferedReader=newbufferedReader(newfilereader(“/PATH/TO/YOUR/FILE.cvs”);
字符串ln;
而((ln=reader.readLine())!=null)
{
字符串[]split=ln.split(“,”);
字符串user=split[0];
Map userMap=userAnswers.get(用户);
if(userMap==null)
{
userMap=newhashmap();
userAnswers.put(user,userMap);
}
put(split[1],split[2]);
}
reader.close();

使用
String.split()

HashMap userAnswers=newhashmap();
BufferedReader=newbufferedReader(newfilereader(“/PATH/TO/YOUR/FILE.cvs”);
字符串ln;
而((ln=reader.readLine())!=null)
{
字符串[]split=ln.split(“,”);
字符串user=split[0];
Map userMap=userAnswers.get(用户);
if(userMap==null)
{
userMap=newhashmap();
userAnswers.put(user,userMap);
}
put(split[1],split[2]);
}
reader.close();

在这里,我编写了一个方法,在该方法中,您可以提供文件(.csv)名称作为参数,并获得
HashMap

public Map<String, String> putYourCSVToHashMap(String prm_csvFile) {

BufferedReader br = null;    //bufferReader
String line = "";
HashMap<String,Map<String, String>> hMapData = new HashMap<>();
Map<String, String> userMap;  //refering to inner Hashmap.
String cvsSplitBy = ","; //parameter on which your csv lines is splitted as an Array.

try {   
   br = new BufferedReader(new FileReader(prm_csvFile)); // Read Your File and Stored into BufferedReader.

while ((line = br.readLine()) != null) { //read each Line of File till last.

    String[] csv_LineAsArray= line.split(cvsSplitBy); //each line will is splitted into an String Array.

    String username = csv_LineAsArray[0]; //pick username available at 0th Index.

    userMap= hMapData.get(username);

    if(userMap == null) //if perticular user doesnot have any record
      {
//Create a New Object for each new line where Question as a key Answer as a Value.
        userMap = new HashMap<String, String>(); 
        hMapData.put(user, userMap);
      }

    // put question as a key and Answer as a Value.    
     userMap.put(csv_LineAsArray[1], csv_LineAsArray[2]);
 }

    } catch (FileNotFoundException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return hMapData;   // return your csv file as a HashMap.
}
公共映射putYourCSVToHashMap(字符串prm\u csvFile){
BufferedReader br=null;//bufferReader
字符串行=”;
HashMap hMapData=新的HashMap();
Map userMap;//引用内部Hashmap。
字符串cvsSplitBy=“,”;//将csv行拆分为数组的参数。
试试{
br=new BufferedReader(new FileReader(prm_csvFile));//读取文件并存储到BufferedReader中。
而((line=br.readLine())!=null){//读取文件的每一行,直到最后一行。
String[]csv_LineAsArray=line.split(cvsSplitBy);//每行将被拆分为一个字符串数组。
字符串username=csv_LineAsArray[0];//选择第0个索引中可用的用户名。
userMap=hMapData.get(用户名);
if(userMap==null)//如果特定用户没有任何记录
{
//为每个新行创建一个新对象,其中问题作为关键答案作为值。
userMap=newhashmap();
hMapData.put(user,userMap);
}
//把问题作为关键,把答案作为价值。
put(csv_LineAsArray[1],csv_LineAsArray[2]);
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(br!=null){
试一试{
br.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
return hMapData;//将csv文件作为HashMap返回。
}

在这里,我编写了一个方法,在该方法中,您可以提供文件(.csv)名称作为参数,并获得
HashMap

public Map<String, String> putYourCSVToHashMap(String prm_csvFile) {

BufferedReader br = null;    //bufferReader
String line = "";
HashMap<String,Map<String, String>> hMapData = new HashMap<>();
Map<String, String> userMap;  //refering to inner Hashmap.
String cvsSplitBy = ","; //parameter on which your csv lines is splitted as an Array.

try {   
   br = new BufferedReader(new FileReader(prm_csvFile)); // Read Your File and Stored into BufferedReader.

while ((line = br.readLine()) != null) { //read each Line of File till last.

    String[] csv_LineAsArray= line.split(cvsSplitBy); //each line will is splitted into an String Array.

    String username = csv_LineAsArray[0]; //pick username available at 0th Index.

    userMap= hMapData.get(username);

    if(userMap == null) //if perticular user doesnot have any record
      {
//Create a New Object for each new line where Question as a key Answer as a Value.
        userMap = new HashMap<String, String>(); 
        hMapData.put(user, userMap);
      }

    // put question as a key and Answer as a Value.    
     userMap.put(csv_LineAsArray[1], csv_LineAsArray[2]);
 }

    } catch (FileNotFoundException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return hMapData;   // return your csv file as a HashMap.
}
公共映射putYourCSVToHashMap(字符串prm\u csvFile){
BufferedReader br=null;//bufferReader
字符串行=”;
HashMap hMapData=新的HashMap();
Map userMap;//引用内部Hashmap。
字符串cvsSplitBy=“,”;//将csv行拆分为数组的参数。
试试{
br=new BufferedReader(new FileReader(prm_csvFile));//读取文件并存储到BufferedReader中。
而((line=br.readLine())!=null){//读取文件的每一行,直到最后一行。
String[]csv_LineAsArray=line.split(cvsSplitBy);//每行将被拆分为一个字符串数组。
字符串username=csv_LineAsArray[0];//选择第0个索引中可用的用户名。
userMap=hMapData.get(用户名);
if(userMap==null)//如果特定用户没有任何记录
{
//为每个新行创建一个新对象,其中问题作为关键答案作为值。
userMap=newhashmap();
hMapData.put(user,userMap);
}
//把问题作为关键,把答案作为价值。
put(csv_LineAsArray[1],csv_LineAsArray[2]);
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(br!=null){
试一试{
br.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
return hMapData;//将csv文件作为HashMap返回。
}

我将按照“尽可能简单”的原则告诉您我将如何做

我已经阅读了其他答案,我认为使用String.split是个坏主意,因为您确切地知道在CSV文件的每一行中查找值的位置。 更好的方法是使用子字符串

这是一个完整的解决方案

我们创建类元组来存储Q/A元组。(我不使用地图,因为它是一种过度使用:))

这是一个简单的类,但它将在以后为您节省大量代码

现在让主班来做所有的工作

课堂提问{ 私有最终地图csvData

    public Questions() {
        csvData = new HashMap<String, Tuple>();
    }

    public void setUserChallengeValues(String line) {
        String name = "";
        String question = "";
        String answer = "";

        name = line.substring(0, line.indexOf(","));
        line = line.substring(line.indexOf(",") + 1);
        question = line.substring(0, line.indexOf(","));
        line = line.substring(line.indexOf(",") + 1);
        answer = line;
        this.csvData.put(name, new Tuple(question, answer));
    }
}
如果需要完整的代码片段,请告诉我


祝你好运:)

我会告诉你我将如何做,遵循“尽可能简单”的原则

我已经阅读了其他答案,我认为使用String.split是个坏主意,因为您确切地知道在CSV文件的每一行中查找值的位置。 更好的方法是使用子字符串

这是一个完整的解决方案

我们创建类Tuple来存储Q/A Tuple(我不使用map,因为它是一个
    public Questions() {
        csvData = new HashMap<String, Tuple>();
    }

    public void setUserChallengeValues(String line) {
        String name = "";
        String question = "";
        String answer = "";

        name = line.substring(0, line.indexOf(","));
        line = line.substring(line.indexOf(",") + 1);
        question = line.substring(0, line.indexOf(","));
        line = line.substring(line.indexOf(",") + 1);
        answer = line;
        this.csvData.put(name, new Tuple(question, answer));
    }
}
  Questions questions = new Questions();

  //Feed the lines here one by one
  String line1 = "User1,What is your favorite color?,color";
  questions.setUserChallengeValues(line1);