Mehdi
Mehdi

Reputation: 2228

Retrieve position from HashMap

I research a position of my key in hashMap. Example :

    HashMap<Integer, String> ht = new HashMap();
    ht.put(1, "c");
    ht.put(10, "b");
    ht.put(8, "r");

    System.out.println(ht);

10 has position 3 in HashMap, 8 has position 2 ...

So I have two questions :

  1. how to retreive these positions from HashMap?
  2. When i have a much element, i use hashMap to retreive a positions or Binary Search ?

Upvotes: 1

Views: 175

Answers (2)

Dan D.
Dan D.

Reputation: 32391

HashMap is not a sorted or ordered Map implementation, so there isn't a "position" here.

LinkedHashMap is an ordered one, TreeMap is a sorted one.

Upvotes: 13

Jeff Storey
Jeff Storey

Reputation: 57212

A hash map is not ordered, so there are no real concepts of positions in a hashmap. If you need an ordered/sorted map, have a look at TreeMap or LinkedHashMap.

Upvotes: 2

Related Questions