Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Maintain order of insertion [duplicate]

I want to add a key, value pair into a hashtable (or any other collection) but have to maintain insertion order. How can I do this?

Like I'll add 1 as key "one" as value, 2 as key and "two" as value.

The output should be:

1:one
2:two
like image 661
sarah Avatar asked Jun 04 '10 11:06

sarah


People also ask

How do you preserve insertion order in a Set?

Use LinkedHashSet if you want to maintain insertion order of elements. Use TreeSet if you want to sort the elements according to some Comparator.

Which Following maintain insertion order and accept duplicates entries?

Which of the following Sets maintains the insertion order? LinkedHashSet maintains the order in which the elements are inserted.

Which collection maintains the order of insertion?

ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.

Can we maintain insertion order in Set?

HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements. We can not predict the insertion order in HashSet, but we can predict it in LinkedHashSet. The LinkedHashSet extends the HashSet, so it uses a hashtable to store the elements.


2 Answers

Here are the characteristic differences of some important Map implementations:

  • LinkedHashMap: "with predictable iteration order [...] which is normally the order in which keys were inserted into the map (insertion-order)."
  • HashMap: "makes no guarantees as to the order of the map"
  • TreeMap: "is sorted according to the natural ordering of its keys, or by a Comparator"
    • i.e. it's a SortedMap

So it looks like LinkedHashMap is what you need in this case.

Here's a snippet to illustrate the differences; it also shows a common way to iterate over all entries of a Map, and how using an interface to refer to objects allow great flexibility of choice of implementation.

import java.util.*;
public class MapExample {
    public static void main(String[] args) {
        populateThenDump(new HashMap<String,Integer>());
        populateThenDump(new TreeMap<String,Integer>());
        populateThenDump(new LinkedHashMap<String,Integer>());
    }
    static void populateThenDump(Map<String,Integer> map) {
        System.out.println(map.getClass().getName());

        map.put("Zero",  0);
        map.put("One",   1);
        map.put("Two",   2);
        map.put("Three", 3);
        map.put("Four",  4);

        for (Map.Entry<String,Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
    }
}

The output of the above snippet is (as seen on ideone.com):

java.util.HashMap          // unordered, results may vary
Three => 3
Zero => 0
One => 1
Four => 4
Two => 2
java.util.TreeMap          // ordered by String keys lexicographically
Four => 4
One => 1
Three => 3
Two => 2
Zero => 0
java.util.LinkedHashMap    // insertion order
Zero => 0
One => 1
Two => 2
Three => 3
Four => 4

Related questions

  • Iterate Over Map
  • iterating over and removing from a map
    • If you want to modify the map while iterating, you'd need to use its Iterator.

Similar questions

  • How to keep the order of elements in hashtable
  • Does entrySet() in a LinkedHashMap also guarantee order?
  • Java Class that implements Map and keeps insertion order?
  • Ordered List Map implementation in Java
like image 137
polygenelubricants Avatar answered Oct 16 '22 17:10

polygenelubricants


For hash table, use LinkedHashMap class.

like image 11
Peter Štibraný Avatar answered Oct 16 '22 17:10

Peter Štibraný