Meenakshi
Meenakshi

Reputation: 468

How to Check the Hashmap's First element?

  if(callingflag)
            {
                int calledUserTp = totalPointsByUserid(callinguserid,jokercard);
                System.out.println("Total Points of the User Who has made a Call is ::"+calledUserTp);

            HashMap<Integer,Integer> useridTotalRankMap = totalPointsforEveryUser(jokercard);
            HashMap<Integer,Integer> useridTotalRankMapSorted = new HashMap<Integer, Integer>();
            useridTotalRankMapSorted = (HashMap<Integer, Integer>) sortByComparator(useridTotalRankMap);
            for(Map.Entry<Integer, Integer> entry :useridTotalRankMapSorted.entrySet())
            {
                System.out.println( entry.getKey() +"----"+entry.getValue());
                if(entry.getKey() == callinguserid )
                {
                    System.out.println( "GOOD CALL");
                    break;
                }

            }
    }

How can I avoid the for loop mentioned above . useridTotalRankMapSorted is a Map

I have this hashmap called useridTotalRankMap it will have userid with some totalpoints.

I want to check if the value corresponding to calleruserid is the least in that hashmap provided there are no ties.

say ther is

1:4
4:7
3:7
2:5

and calleruserid = 1 . I print "good call" if the value of key=1 ie 4 is the minimum.

Hope I am clear now.

is there any change in the way I am coding?

Upvotes: 1

Views: 2595

Answers (7)

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

You could do it with sorted Maps like TreeMap, and the easiest way to get the first element would be with the iterator (if you want to hold the insertion order LinkedHashMap):

Map m = new TreeMap(); // get it from somewhere else otherwise it doesn't make sense
Set s = m.entrySet();
Iterator i = s.iterator();
if (i.hasNext()) {
    Object firstElement = i.next();
}

Upvotes: 3

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. HashMap is a class which do Not implement Sorted Map Interface.

2. UseTreeMap if you want to fetch the data in Order.

3. Use LinkedHashMap if you want nodes linked to each other and then fetch the 1st element.

Upvotes: 0

Aviram Segal
Aviram Segal

Reputation: 11120

First, as everybody else said, HashMap is not sorted.

Second, as key in Map is unique (can't map key to more than one value).

Why don't you just get from the map (map.get(callinguserId)), what did you gain by iterating on entries ?

That if will only be true once anyway.

Upvotes: 0

Jon Newmuis
Jon Newmuis

Reputation: 26492

HashMaps do not guarantee order.

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

From http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html


To maintain insertion order, you should use a LinkedHashMap.

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.

From http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html


To maintain a sort order (natural sort ordering, or as defined by a Comparator), you should use any class that implements SortedMap.

A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views

From http://docs.oracle.com/javase/6/docs/api/java/util/SortedMap.html

Upvotes: 2

mlishn
mlishn

Reputation: 1667

You would need to create a LinkedHashMap to get the first inserted element

Then ->

useridTotalRankMapSorted.entrySet().iterator().next().getKey()
useridTotalRankMapSorted.entrySet().iterator().next().getValue()

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200148

Use useridTotalRankMapSorted.entrySet().iterator().next() to access the first item. Better make sure you are indeed using a sorted map!

Upvotes: 3

nfechner
nfechner

Reputation: 17525

A HashMap is not sorted. It has no first element.

Upvotes: 5

Related Questions