1

I am pretty new to Lists, Queues, etc.

I want to take every value within key i and add/subtract 1 to each one and give them key i+1, then take every value from i+1, and so on. For example I imagine that if i input

3

the map would look like Map K, V

0, 3
1, 4 
1, 2
2, 5
2, 3
2, 3
2, 1 -- Now it will end, because !map.containsValue(1) == false

This is the code that I have

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    Integer x = sc.nextInt();
    Integer i = 1;

    map.put(0, x);

    while (!map.containsValue(1)) {

        for (Map.Entry<Integer, Integer> a : map.entrySet()) {
            if (a.getKey().equals(i)) {
                map.put(i++, (x-1));
                map.put(i++, (x+1));
            }
            i++;
        }
    }

I am not fixed to use HashMap, if there is a better solution to this(finding a value using a key, not an index), hit me up! Thanks for your answers.

OhOkay
  • 45
  • 1
  • 5

1 Answers1

0

i++ changes the value of i, not only giving you the i+1

Map.put(key,value) takes a key as the first parameter, not the place in the Map, and the key should be unique. So your desired output is not possible using HashMap. The second time your are trying to insert the same key will override the first entry.

You may want to look at multiple key maps. Or redefine your task.

Another possibility is to use ArrayList of pair by either using the Entry or your own defined Pair as in the example:

Creating a list of pairs in java

Community
  • 1
  • 1
Roman Pustylnikov
  • 1,937
  • 1
  • 10
  • 18
  • Do you think that maybe using 2D array like `array[key][MAX] = value` , and deleting all `array[key][MAX].equals(0)` would be better? – OhOkay Oct 17 '15 at 13:13