0

In an Android application I call a web service, get json response and put that into an ArrayList of Hashmap (each identifier returned in the JSON gets a field.

My list which stores [n] items is defined as:

private ArrayList<HashMap<String, String>> customerDataList;

When I receive the data I create a new Hashmap collection like so:

HashMap<String, String> customer = new HashMap<>();

And then I simply add the values I need for example

JSONObject thisCustomer = customerArr.getJSONObject(customerIndex);

String customerName = thisCustomer.getString(TAG_CUSTOMER_NAME);
customer.put(TAG_CUSTOMER_NAME, customerName);

double location = // get location based on GPS
customer.put(TAG_LOCATION, location);    

// snip...

Then once I have populated that customer object I add it to the list:

customerDataList.add(customer);

Now, I want to sort this data by one value, the location which I set above.

Currently after I have populated customerDataList I loop through it, build an array of all the locations, sort it, and then loop over the sorted array. Inside that I loop over customerDataList and compare the outer location (the sorted values) with the inner, and build another customerDataList which is sorted.

Is there a way I can sort without needing to have 3 loops?

Edit: Mike does your solution work with doubles?

The unsorted locations are as follows

1513.70
702.59
814.59
604.99

However the final list after I call your class is

1513.70
604.99
702.59
814.59
1
  • I presume that is because I store them as a string? Commented Jan 10, 2015 at 17:24

1 Answer 1

4

If I understood the question correctly it sounds like you could use a custom comparator to sort the array list in the first place:

public class LocationComparator 
             implements Comparator<HashMap<String, String>> 
{
   @Override
   public int compare(HashMap<String, String> o1, 
                      HashMap<String, String> o2) 
   {
       return Double.compare(o1.get(TAG_LOCATION), o2.get(TAG_LOCATION));
   }
}

Collections.sort(customerDataList, new LocationComparator());

And of course, you could use an anonymous class to implement the Comparator<> interface inline.

But as an aside, why are you storing your customer entities in hash maps? It seems wasteful..

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it. No reason to sort with nested loops, when a cleaner implementation exists.
Look at the JavaDocs, the mothod takes two doubles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.