Maps (collection) that maintains insertion Order in java

☆樱花仙子☆ 提交于 2019-12-22 03:48:07

问题


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.


回答1:


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




回答2:


The LinkedHashMap maintains insertion order.




回答3:


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




回答4:


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);



回答5:


use LinkedHashMap. please follow this link for more details



来源:https://stackoverflow.com/questions/9552822/maps-collection-that-maintains-insertion-order-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!