0

For my schooling I have to write a programm, which read and return costumer value from data. To do that, I have created an double hash map. In the inner, i have mapped for example, keys like name, to values like chris. The outer map is for mapping the inner maps, to the costumers name.

To create a list of the accessible files/costumers, I have created that code:

for (HashMap<String, String> file: output.MapForFileMaps.values())
    {
        h = h + 1;
        if (fileRequest == h)
        {
            requestIsListet = true;
            for (String key: file.keySet())
            {
                p = p + 1;
                System.out.println("Press " + p + " for " + key);
            }
        }
    }

Question: Could I reach directly that part of the hash map, which is needed, by asking for the value or key of the hash map on the n`th place?

Current Problem is, that I want to check wheather the input is connected to a accessible part of the map, or not. So I could return this area of code by an while loop, while request is not available.

  • 3
    There is no guarantee the nth value is going to be the same over multiple iterations for a HashMap. See: https://stackoverflow.com/questions/2144776/is-the-order-of-values-retrieved-from-a-hashmap-the-insertion-order – Compass Nov 20 '18 at 14:37
  • 2
    It seems you're using wrong data structure for the problem because, by definition, there is no Nth key/value in hash map. – TheJavaGuy-Ivan Milosavljević Nov 20 '18 at 14:38
  • What’s wrong with designing a proper `Customer` class with instance variables (fields) for name, etc.? In case it helps you. a `LinkedHashMap` maintains insertion order, so you may use its iterator to count to the *n*th inserted item (provided that no item has later been removed again). – Ole V.V. Nov 20 '18 at 15:09

1 Answers1

1

Question: Could I reach directly that part of the hash map, which is needed, by asking for the value or key of the hash map on the n`th place?

Answer: You COULD, but it wouldnt be efficcient, Hashmaps store elements based on a hash of the key, so the first inserted element isnt per definition on index 0. You can instead use the key to get the value

Take a look here: https://www.geeksforgeeks.org/internal-working-of-hashmap-java/

Teun van der Wijst
  • 939
  • 1
  • 7
  • 21