Correctly fill in the list on the map
I have a map whose value is a list of integers. I have to add an integer to the list if the key is found in the reader. The code I have below works every time except one. In other words, if the key exists 5 times, the list will say it only has 4 times. What am I missing? Thank!
Map<String, List<Integer>> map = new TreeMap<String, List<Integer>>();
String key; // the string from my reader
if (map.containsKey(key)) {
map.get(key).add(value); //value being an integer gotten earlier
}
My code has keys that are added to the map in a constructor like this:
while (reader.ready()) {
key = reader.readLine();
if(!key.isEmpty()) {
map.put(key, new ArrayList<Integer>());
}
}
I don't need to do anything if the key is not found, just add the value when it is.
source to share
The scanned code snippet is not your complete complete code, but you need to have logic anyway to handle the first time the key is displayed. In this first case, you must initialize the list of integers to be stored in the card. Something like that:
public static void addValue(String key, Integer value,
Map<String, List<Integer>> map) {
List<Integer> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
}
list.add(value);
}
public static void main(String[] args) {
Map<String, List<Integer>> map = new TreeMap<String, List<Integer>>();
String key; // the string from my reader
Integer value;
addValue(key, value, map);
}
source to share
How do you cope if the key is not found? I suspect you were unable to add the first Integer value to the list if the key is not found.
if (map.containsKey(key)) {
map.get(key).add(value); //value being an integer gotten earlier
} else {
List<Integer> list = new ArrayList<>();
list.add(value); //add value to the list
map.put(key, list);
}
source to share
hope this helps you solve the problem.
//if key not exists insert key
if(!map.containsKey(key)){
List<Integer> list = new ArrayList<Integer>();
list.add(value);
map.put(key,list);
}
//if key exists do this...
else{
List<Integer> list = new ArrayList<Integer>();
//Getting previous existing elements on map at that index and adding to list back
list.addAll(map.get(key));
map.put(list);
}
source to share