Java Class that implements Map and keeps insertion order?

后端 未结 9 2040
一向
一向 2020-11-22 11:28

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<
相关标签:
9条回答
  • 2020-11-22 11:46

    LinkedHashMap will return the elements in the order they were inserted into the map when you iterate 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 will print the elements in the order they were put into the map:

    id = 1
    name = rohan 
    age = 26 
    
    0 讨论(0)
  • 2020-11-22 11:52

    You can use LinkedHashMap to main insertion order in Map

    The important points about Java LinkedHashMap class are:

    1. It contains onlyunique elements.
    2. A LinkedHashMap contains values based on the key 3.It may have one null key and multiple null values. 4.It is same as HashMap instead maintains insertion order

      public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 
      

    But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link

    0 讨论(0)
  • 2020-11-22 11:53

    Whenever i need to maintain the natural order of things that are known ahead of time, i use a EnumMap

    the keys will be enums and you can insert in any order you want but when you iterate it will iterate in the enum order (the natural order).

    Also when using EnumMap there should be no collisions which can be more efficient.

    I really find that using enumMap makes for clean readable code. Here is an example

    0 讨论(0)
提交回复
热议问题