Reputation: 3095
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
Upvotes: 0
Views: 576
Reputation: 55760
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..
Upvotes: 4