user12314100
user12314100

Reputation:

Java HashMap add key +1 to every new Value?

I´m writing a programm in Java. This programm should handle with a lot of diffrent values. I decided to use a HashMap, as you can see here :

public static Map<String, Map<Integer, String>> users = new HashMap<>();

So, as you see I´ve got a map with 2 keys. The first key decides about my "second HashMap". I hope you understood that, because now here is my problem.

public class test {

public static Map<Plot, Map<Integer, Player>> users = new HashMap<>();
public void test(String first, String second) {

if(users.get(first).isEmpty() {
users.computeIfAbsent(first, (a)->new HashMap<>()).put(0, null);
}

if(!users.get(first).containsValue(second)) {
users.computeIfAbsent(first, (a)->new HashMap<>()).put(/*my problem*/, second);
    }
  }
}

So, in the last if-statement is a comment. I don´t know what i should write in there ? This method is called by another class, but that doesnt matter. My goal is, that to every String (first Key) will be saved a certain Integer (second key) with a certain value(second String in my method). Of course I want every String to start with 0 and have its own chronologically order. But remember, you can´t use at the start of the class a normal Integer-var, because if you should use it for every key it wouldn´t solve my problem.

Upvotes: 0

Views: 1144

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103608

If I understand you correctly, the 'inner map' (the one with type Map<Integer, String>) will at all times adhere to the following rule:

The map's keys will always cover a closed range from 0 to its size. For example, an inner map of size 8 will have as keys: `[0, 1, 2, 3, 4, 5, 6, 7].

Assuming I parsed your question correctly, you.... made a list. A list IS semantically speaking exactly that: A thing that 'maps' a closed range of integers starting from 0 to values. To read from this 'map' the value associated with 'key' 5, you just call list.get(5). To 'add' an item at the end, you just call list.add(x) instead of map.put(???, x).

Thus, the answer is as trivial as: Replace Map<Integer, String> with List<String>, replace the (a)->new HashMap<>() with a->new ArrayList<>(), and replace .put(/*my problem*/, with .add(.

If you must do this with maps, you cannot do it with hashmaps, unless you try to use map.size() as a fragile standin, which I strongly advise you don't do (as that would imply your map only works in cases where list would be better, thus proving that the map solution is inferior) – hashmaps do not have an order and thus no idea of 'what is the last / highest key'. You can use a TreeMap instead, which DOES have such concepts. You can ask it about the highest key, and then use 1 higher than that.

But I'm pretty sure you just want a list here.

Upvotes: 2

Related Questions