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.

+3


source to share


4 answers


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);
}

      

0


source


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);
}

      

0


source


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);
        }

      

0


source


You didn't mention that you want to change the same list which is not just the map value, only if it is the same list you can use java 8

map.entrySet().forEach(entry -> {
        if ("5" == entry.getKey()) {
            ((List) entry.getValue()).add(5);
            System.out.println(entry.getValue());
        }
});

      

0


source







All Articles