Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (5.3k points)

I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:

  1. Add values to a Hashtable.

  2. Get an iterator for the Hashtable.entrySet().

  3. Iterate through all values and:

    1. Get a Map.Entry for the iterator.

    2. Create an object of type Module (a custom class) based on the value.

    3. Add the class to a JPanel.

  4. Show the panel.

The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).

I would use an ArrayList or Vector for this, but later in the code I need to grab the Module object for a given Key, which I can't do with an ArrayList or Vector.

Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable based on when they were added?

Thanks!

1 Answer

0 votes
by (119k points)

LinkedHashMap will display the values in the order they were inserted into the map when you iterate them over the keySet(), entrySet() or values() of the map.

Map<String, String> map = new LinkedHashMap<String, String>();

map.put("id", "1");

map.put("name", "rohan");

map.put("age", "26");

for (Map.Entry<String, String> entry : map.entrySet()) {

    System.out.println(entry.getKey() + " = " + entry.getValue());

}

This code will return the values in the order they were put into the map:

id = 1

name = rohan 

age = 26 

If you want to learn Java from the top experts, I recommend this Java Training program by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 17, 2021 in Java by Jake (7k points)

Browse Categories

...