How To Get Two Values Of String In A Single Hashmap?
Solution 1:
Indeed, this is a java question. There are many ways you can do this.
HashMap<String, String[]> map = new HashMap<String, String[]>();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
Create a class or enum(preferred) for example TAG, which has two string fields, then
Map<String, TAG> map = new HashMap<String, TAG>();
Since your updated question is a little bit unclear, I tried to answer this based on my own understanding. I think what you want to do is continously getting questions and their answers.
So may be you can try another approach:
classQuestion{
String questionText;
String answer;
...
}
//map from questionID to a questionMap<String, Question> questionMap = newHashMap<String, Question>();
//TODO: fill up the map with existing questions.Question question = questionMap.get(questionID);
System.out.println("Question:" + question.questionText + " Answer:" + question.answer);
//same for another question
Solution 2:
Use value separated by delimiters and split them later.
HashMap<String, String> map1 = newHashMap<String, String>();
map1.put(TAG_ANSW, ""+answer+":"+"questionid");
Then when you retrieve it just split them:
x= map1.get(TAG_ANSW)
String [] ans_questionId = x.split();
store them to their respective values...
Solution 3:
HashMap<String, ArrayList<String>> multiMap =
newHashMap<String, ArrayList<String>>();
voidput(String key, String value) {
ArrayList<String> values = multiMap.get(key);
if (values == null) {
values = newArrayList<String>();
multiMap.put(values);
}
values.add(value);
}
ArrayList<String> get(String key) {
ArrayList<String> value = multiMap.get(key);
return value;
}
// Need to specify also which value to removevoidremove(String key, String value) {
ArrayList<String> values = multiMap.get(key);
if (values != null) {
values.remove(value);
if (values.size() == 0)
multiMap.remove(key);
}
}
If you do not want to keep repetitive values for the same key, use HashSet
instead of ArrayList
. In any case you get back a collection of all values you have ever stored under this key.
Post a Comment for "How To Get Two Values Of String In A Single Hashmap?"