如何在hashmap中将内容放入hashmap中

时间:2016-04-20 10:46:31

标签: 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 your first best friend's name?,friend

我需要调用OIM API,它将采用这样的参数

void setUserChallengeValues(java.lang.String userID,
                        boolean isUserLogin,
                        java.util.HashMap quesAnsMap)

其中quesAnsMap参数表示挑战问题和答案的HashMap

使用userid的hashmap作为键解析CSV文件以及将问题和答案作为值来解析CSV文件的有效方法是什么?

我的hashmap应该像User1是关键值,值应该是问题作为键,并作为值回答。

要引用的任何示例代码段吗?

由于

3 个答案:

答案 0 :(得分:2)

逐行阅读文件,将其分成','使用String.split()

HashMap<String, Map<String, String>> userAnswers = new HashMap<>();
BufferedReader reader = new BufferedReader(new FileReader("/PATH/TO/YOUR/FILE.cvs"));
String ln;
while((ln = reader.readLine()) != null)
{
    String [] split = ln.split(",");
    String user = split[0];
    Map<String, String> userMap = userAnswers.get(user);
    if(userMap == null)
    {
        userMap = new HashMap<String, String>();
        userAnswers.put(user, userMap);
    }

    userMap.put(split[1], split[2]);
}

reader.close();

答案 1 :(得分:0)

这里我正在编写一种方法,您可以在其中提供文件(.csv)名称作为参数,并将HashMap<String, String>作为结果

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.
}

答案 2 :(得分:0)

我将告诉你我将如何做到这一点,遵循“尽可能保持简单”的原则。

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

所以这是一种完整的解决方案。

我们创建了用于存储Q / A元组的类Tuple。 (我没有使用地图,因为它太过分了:))

class Tuple {
public String question;
    public String answer;

    public Tuple(String question, String answer) {
        this.question = question;
        this.answer = answer;
    }
}

它是一个简单的类,但稍后会为你节省大量的代码。

现在主要班级要做所有工作。

课堂问题{     私人最终地图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));
    }
}

有你的方法,逻辑非常简单(在我看来与分裂相比简单得多)。你只需要寻找“,”的索引。 这样您就可以轻松地从每一行中提取姓名,问题和答案。

最后,实际的解析变成了几行代码。

  Questions questions = new Questions();

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

如果您需要整个代码段,请告诉我。

祝你好运:)