Store list into map

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


    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

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


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

Or you can use Map#computeIfAbsent

fruitMap.computeIfAbsent(s.toLowerCase(), k -> new LinkedList<>()).add(s);

Source: stackoverflow