How can I add one more value to my Map<Integer>, List<String>>?

Viewed 374

I have this solution to add "c" to my map, but is there another way to do what I want in one line?

Map<Integer, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
map.put(1, list);

list.add("c");
map.put(1, list);
4 Answers

You don't need that last call to map.put(1, list), as list is already the value pointed to by the key 1, so I guess that's a oneliner.

If you meant replacing the entire update of the map with a oneliner, you could use something like Arrays.asList:

map.put(1, Arrays.asList("a", "b", "c"));

I would recommend using Map.computeIfAbsent. If the key is absent or points to a null the supplied value will be used (in this case an ArrayList<String> instance) and return it, otherwise it uses the one already present.

Map<Integer, List<String>> map = new HashMap<>();

map.computeIfAbsent(1, v -> new ArrayList<>()).add("a");
map.computeIfAbsent(1, v -> new ArrayList<>()).add("b");
map.computeIfAbsent(2, v -> new ArrayList<>()).add("b");
map.computeIfAbsent(1, v -> new ArrayList<>()).add("c");
map.computeIfAbsent(2, v -> new ArrayList<>()).add("e");
map.computeIfAbsent(3, v -> new ArrayList<>()).addAll(List.of("f","g","h"));
map.computeIfAbsent(3, v -> new ArrayList<>()).add("i");
                       
map.entrySet().forEach(System.out::println);

Prints

1=[a, b, c]
2=[b, e]
3=[f, g, h, i]
1=[a, b, c]
2=[e, f, g]

You can of course use lambdas or explicit methods to facilitate the process

UPDATED

You can use Stream.of() to create the initial list. After that if you want to add new values only it's necessary add to the list because the reference of the object is the same.

List<String> list = Stream.of("a", "b");
map.put(1, list);
list.add("c");

If you want to do it after declaration you can do this

        Map<Integer, List<String>> map = new HashMap<>();
        map.put(1,List.of("a","b","c"));

At declaration you may do

Map<Integer, List<String>> map = new HashMap<>(Map.of(1,List.of("a", "b", "c")));

In case you don't know how to access a specific element on the list should you need to, you'd do it like

map.get(1).get(i)

where i, is the index of the list

Related