0

I am using maps and I need them to keep the order objects were put into them but they keep sorting themselves at their will. How do I stop that or is there another collection for that? I got around it by using two ArrayLists but I want to do it with one collection.

import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("b", "Item One");
        map.put("a", "Item Two");
        map.put("c", "Item Three");
        System.out.println(map);
    }
}
usama8800
  • 893
  • 3
  • 10
  • 20
  • See this previous question http://stackoverflow.com/questions/683518/java-class-that-implements-map-and-keeps-insertion-order – DHall Jun 13 '14 at 14:06
  • 5
    Use a [LinkedHashMap](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html) to preserve insertion order. – Daniël Knippers Jun 13 '14 at 14:06
  • They are not sorting themselves. This is a property of a/the hash function that is the basis for Maps and Sets. Look at [`LinkedHashMap`](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html) if you want to preserve insertion order. – Hunter McMillen Jun 13 '14 at 14:07
  • See also http://stackoverflow.com/questions/21974361/what-java-collection-should-i-use – Tim B Jun 13 '14 at 14:10

2 Answers2

1

It's a hash map therefore the elements are "sorted" by their hash values. You could use LinkedHashMap

maczikasz
  • 1,113
  • 5
  • 12
0

Think of a map as an array indexed by the key. It's not so much "Sorting" as placing the value at the key you specified.

If you want to keep track of order, I'd recommend creating a list of tuples (or any other object to store both fields) to which you append each data set.

Adam Yost
  • 3,616
  • 23
  • 36