This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Debug note < Implement Map and maintain insert order Java classes? >

Ask questions

Java classes that implement Map and maintain insertion order?

I’m looking for Java classes that have key-value associations, but don’t use hashes. Here’s what I’m doing right now:

  1. Adds the value toHashtable.
  2. Iterator to getHashtable.entrySet().
  3. Iterate over all values and:
  • Map.EntryGet one for the iterator.
  • ModuleCreates an object of type (custom class) based on this value.
  • Add the class toJPanel.
  1. Display panel.

The problem with this is that I have no control over the order in which I get the values, so I can’t display them in a given order (without hard-coding the order). I’ll use an ArrayListor Vector for this, but later in the code I need to get the object with the Key given to the Module, which for ArrayListor is not a Vector. Does anyone know if a free/open source Java class could do this, or if Hashtable is a way to get values from added values?

Answer a:

I suggest a LinkedHashMap or a TreeMap. ALinkedHashMap maintains the insertion order of keys, while aTreeMap sorts through the natural order of aComparator or Comparable elements. Since you don’t have to sort elements, the LinkedHashMap should be faster in most cases. TreeMap has O(log n) representing containsKey, get, PUT, and remove. If your API expects only predictable sort order, rather than a specific sort order, consider using the interfaces implemented by these two classes, NavigableMap or SortedMap. That way, you don’t leak specific implementations into your API and can then switch to those specific classes or completely different implementations.

Answer two:

When you iterate through a Map’s keySet (), entrySet (), or values (),

LinkedHashMap will return elements in the order they were inserted into 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());
}
Copy the code

This will print in the order in which the elements are placed on the map:

id = 1
name = rohan 
age = 26 
Copy the code

The article translated from Stack Overflow: stackoverflow.com/questions/6…