Skip to content
Advertisement

Store list into map

[Can you help me to get what was wrong with the below program]

Code

    List<String> fruitsList= new LinkedList<>(Arrays.asList("mango", "apple", "grapes","MANGO", "APPLE", "GRAPES"));
    Map<String, List<String>> fruitMap = new HashMap<>();
    for (String s : fruitsList) {

        if (fruitMap.get(s.toLowerCase())==null) {

            fruitMap.put(s.toLowerCase(), Collections.singletonList(s));
        } else {
             fruitMap.get(s.toLowerCase()).add(s);  // got error at this line
        }
    }
    System.out.println(fruitMap);

Expected map: {apple=[apple,APPLE], mango=[mango,MANGO], grapes=[grapes,GRAPES]}]

Advertisement

Answer

Collections.singletonList returns an immutable list and hence you cannot add elements into it. Create a list which is mutable.

Simplifying it,

if (fruitMap.get(s.toLowerCase()) == null) {
    fruitMap.put(s.toLowerCase(), new LinkedList<>());
}
fruitMap.get(s.toLowerCase()).add(s);  

Or you can use Map#computeIfAbsent

fruitMap.computeIfAbsent(s.toLowerCase(), k -> new LinkedList<>()).add(s);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement