Rizky A Fauzan
Rizky A Fauzan

Reputation: 51

How to insert another element into TreeMap value as a List

so im still learning about Java mapping and just wondering is it possible to insert another element into TreeMap value as a List? So here's my code:

TreeMap<String,List<Integer>> myTree = new TreeMap<>();

String info = "Andi 20";
Integer extra = 100;

String[] temp = info.split(" ");
myTree.put(temp[0], Collections.singletonList(Integer.parseInt(temp[1])));  // {Andi : [20]}

how to insert another element (for example : Integer extra) into a list of value? so the output will look like this :

// {Andi : [20,100]}

if it possible, maybe can you give the detail about the time complexity too?? it will help me a lot

Thank you everyone...

Upvotes: 0

Views: 1393

Answers (1)

C. McKinnon
C. McKinnon

Reputation: 277

As long as the List implementation you're using supports add, of course you can add additional elements.

But, you're using Collections#singletonList, which by definition does not allow any modifications (the singleton collections utilities return immutable implementations). Just use ArrayList, LinkedList, etc.

Map<String,List<Integer>> map = new TreeMap<>();
map.put("foo", new ArrayList<>());
map.get("foo").add(1);
map.get("foo").add(2);

The time complexity for get and put are in the TreeMap documentation:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

The time complexity of map.get("foo").add(1) is log(n), because ArrayList#add is constant-time.

You can make use of Map#computeIfAbsent to handle initializing the List:

map.computeIfAbsent("foo", key -> new ArrayList<>()).add(1);

Note that computeIfAbsent is preferable to putIfAbsent in any case where new is used, because computeIfAbsent avoids an unnessary allocation when the key already exists in the map.

Upvotes: 2

Related Questions