Search code examples
javahashmapconcurrenthashmaplinkedhashmap

which one is better to sort linked items , Hashmap or linkedhashmap or any other?


I have 2 strings from twitter JSON "follower_count" and "user id"

i need something to sort them according to favourite count in descending order, i.e with greater Follower count gets placed first and then access their "user id" link. and print from 1 to 10.

Best way to do that in java/android with hashmap or linked hashmap or any other ?

Update:- i used sorted maps as suggested, actually Treemap

here is my progress so far:

//get  the first status
        status = statuses.get(0);
     //get id of the status
          long l= status.getId(); 
        //get retweeters id
          ki =twitter.getRetweeterIds(l, 100, -1);

         long[] id=ki.getIDs();
         //for every retweeter id, get followers count and put in treemap
         TreeMap<Integer,Long> tm = new TreeMap<Integer, Long>();
         for(int k=0;k<=id.length;k++)
         {
             u = twitter.showUser(id[k]);
             follower=u.getFollowersCount();
             tm.put(follower,id[k] );
         }
NavigableMap<Integer,Long> reverseTreeMap = tm.descendingMap();

Solution

  • Finally i was able to do that by using Treemaps(sorted maps) as suggested in the other answers, thing about tree map is they automatically sort the values by keys. I.e

    Treemap<Integer,String> tree =new Treemap<Integer, String>();
        //now put items in it
         tree.put(5,"hello" );
         tree.put(4,"hello again" );
         tree.put(6,"Goodbye" );  
    

    then when we will take output of that it will come as"

      4=hello again
      5=hello
      6=Goodbye
    

    Now the last task is to reverse that order, for that use

    NavigableMap<Integer,String> reverseTreeMap = tree.descendingMap();
    

    This is my final code, thats how i solved my problem :

     //Using treemap to sort retweeters according to their followers
     TreeMap<Integer,String> tm = new TreeMap<Integer, String>();
     try{
         for(int k=0;k<10;k++)
             {
                 publishProgress(5);
                 Log.i(a, "treemap followers"+k);
                 u = twitter.showUser(id[k]);
                 follower=u.getFollowersCount();
                 url=u.getProfileImageURL();
                 tm.put(follower,url );
             }
        }
    catch(Exception e)
        {
            Log.e(a, e.toString());
        }
    Log.i(a, "Done treemap");
    
     //Reverse the order of the treemap 
     Log.i(a, "Reversing Treemap");
     NavigableMap<Integer,String> reverseTreeMap = tm.descendingMap();
     publishProgress(5);
    
     //Put treemap values in string
     s=reverseTreeMap.values().toString();
     s=s.replace("[", "");
     s=s.replace("]", "");
    
         //make array of string s
         s=s.split(",");
      Log.i(a, "Done");