Akhil K Nambiar
Akhil K Nambiar

Reputation: 3975

Maps (collection) that maintains insertion Order in java

I need to use Maps in Java for an Android Application. But the problem is that the list gets sorted automatically. How do I use Maps to get the data in the same order as I have inserted data.

Upvotes: 15

Views: 8036

Answers (5)

Shashank Kadne
Shashank Kadne

Reputation: 8101

You should use LinkedHashMap for this purpose..Visit Android Docs and Java Docs for more details.

Upvotes: 27

Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

The LinkedHashMap maintains insertion order.

Upvotes: 5

Sishin
Sishin

Reputation: 2001

use LinkedHashMap. please follow this link for more details

Upvotes: 1

Blessed Geek
Blessed Geek

Reputation: 21684

As you and I have discovered, LinkedHashMap isn't very helpful. (What is the point of its existence, anyway?)

I have a hashlist (semantically, I think it should have been called hashedlist)

http://code.google.com/p/synthfuljava/source/browse/trunk/gwt/util/org/synthful/gwt/util/HashList.java

It has an arraylist and a hashmap. The arraylist stores the key.

A hashlist.put(key, value) would perform

  • a map.put(key, value)
  • as well as a list.add(key)

A hashlist.get(int position) would perform - a map.get(list.get(position))

This is a simplification of HashVector and HashTree classes I wrote back in 2003 when I needed to model javascript and xml objects in Java, retaining their order. However, I did not find the time or necessity to simplify the hashtree for gwt serializability.

On second thoughts, how does GWT implement a hashmap? I think when I have the time, I need to replace the hashmap with faststringmap. Google's faststringmap is not public. It is for GWT compiler private use. So you have to copy its code and change it into a public class: http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/user/client/ui/FastStringMap.java

http://jectbd.com/?p=95

May be, GWT compiler would have silently used it anyway - should I bother to micromanage the compiler replace hashmap with faststringmap?

BTW,

You could still look for the hashtree by googling "googlecode synthful hashtree".

The Hashtree allows you to create a tree of objects and allows you to retrieve your objects using the an dot-convention xpath like path.

hashtree.get("hello.dolly.how.are.you");

The separator could be respecified so that you could store or get using

hashtree.get("hello/dolly/how/are/you");
hashtree.put("hello/dolly/how/are/you", value);

Upvotes: 2

talnicolas
talnicolas

Reputation: 14051

A LinkedHashMap will keep the data in the same order as it has been inserted.

Upvotes: 2

Related Questions