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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here are the characteristic differences of some important
Mapimplementations: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 aComparator”SortedMapSo it looks like
LinkedHashMapis 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.The output of the above snippet is (as seen on ideone.com):
Related questions
Iterator.Similar questions