Scorpion
Scorpion

Reputation: 6891

How to Sort HashMap( inside ArrayList) in Android?

I am having Current Location Latitude & Longitude with me. I am getting the list of ATM's near by the user from the Google places API Web Service and storing my data in Arraylist like below.

Code Snippet

double currentLat = xxx;
double currentLang = xxx;

on button click i call the web service of google places.

public void buttonClicked(View v) {
    ParseXMLData xmlData = new ParseXMLData();
    url = baseUrl + "location=" + latitude + "," + longitude + "&" + "radius=" + search_Area_Radius + "&" + "name=" + nameofplace + "&" + "sensor=true" + "&" + "key=" + API_KEY;
    xmlData.execute("");
}

Storing the result inside arraylist....

    for (int i = 0; i < nodes.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element)nodes.item(i);
        map.put("Name", XMLFunctions.getValue(e, "name"));
        map.put("Vicinity", XMLFunctions.getValue(e, "vicinity"));
        map.put("Latitude", XMLFunctions.getValue(e, "lat"));
        map.put("Longitude", XMLFunctions.getValue(e, "lng"));

        loc = new Location("");
        loc.setLatitude(Double.parseDouble(XMLFunctions.getValue(e, "lat")));
        loc.setLongitude(Double.parseDouble(XMLFunctions.getValue(e, "lng")));

Getting the distance b/w 2 points frome here.

        distance = currentLoc.distanceTo(loc);
        map.put("Distance",String.valueOf(distance));
        mylist.add(map);
        loc = null;
        distance = 0.0;
    }

Implemented the Comparator and Sort the ArrayList

public class PositionComparator implements Comparator<HashMap<String, String>> {

    public PositionComparator() {
        // TODO Auto-generated constructor stub
    }


    public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
        /*System.out.println(o1.get("O1 Distance :- "));
        System.out.println(o2.get("O2 Distance :- "));
        System.out.println(o1.get("Distance").compareTo(o2.get("Distance")));
        */
        return o1.get("Distance").compareTo(o2.get("Distance"));
    }
}

Now what happen is the data which i have store inside the arraylist is sorted but the problem is compareTo method sort data based on the 1st character only. Suppose my data is like 2.12345 and 11.32545 then it will replace as 2-1 = 1.

How to solve this?

If anyone has any suggestion/tips for this please kindly help me in this.

Thanks

Upvotes: 2

Views: 3439

Answers (1)

Boris Strandjev
Boris Strandjev

Reputation: 46943

Here goes the thread that describes how you can calculate the distance between to gps coordinates. It features implementations in many languages, hopefully you will understand some of them. Then lets assume you have a function calcDistance that returns Double - the distance from the current point to hash map of your type using its longitude and latitude (btw is it requirement that you use such ugly kind of map? Can't you create a bean class for the same purpose).

Then what you need is to declare a method of comparing two positions specified by their positions:

public class PositionComparator implements Comparator<HashMap<String, String>> {
    public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
        return calcDistance(o1).compareTo(calcDistance(o2));
    }
}

And finally the sorting is done like that:

Collections.sort(mylist, new PositionComparator());

However mind that if you implement the sorting that way the distance to each element will be calculated multiple times. I recommend you to add one more field in the map that stores the distance, so that you avoid reevaluating it.

One last note: if you decide to switch the map with a class, you can easily make this class implement the Comparable interface and define the comparison there.

EDIT Adding the requested example of the bean:

public class PositionBean implements Comparable {
   private double latitude;
   private double longitude;
   private distanceFromCurrentPosition;
   private String vicinity;
   private String name;
   // ...getters and setters ...

   public PositionBean(String latitude, String longitude, String vicinity,
            String name) {
       this.latitude = Double.valueOf(latitude);
       this.longitude = Double.valueOf(longitude);
       this.vicinity= vicinity;
       this.name = name;
       this.distanceFromCurrentPosition = calcDistance();
   }

   public int compareTo(Object anotherPositionObj) throws ClassCastException {
       if (!(anotherPositionObj instanceof PositionBean)) {
           throw new ClassCastException("A PositionBean object expected.");
       }
       int anotherPosition = (PositionBean) anotherPositionObj;  
       return Double.compare(this.getDistanceFromCurrentPosition(),
               anotherPosition.getDistanceFromCurrentPosition());    
   }

   private double calcDistance() {
       //...implement accordingly
   }
}

public static void main(String [] args) {
    List<PositionBean> positions = new ArrayList<PositionBean>();
    // ... Initialize the positions
    Collections.sort(positions);
}

Upvotes: 3

Related Questions