在 Android 应用程序中,我调用 Web 服务,获取 json 响应并将其放入 Hashmap 的 ArrayList 中(JSON 中返回的每个标识符都会获取一个字段。
我的存储 [n] 个项目的列表定义为:
private ArrayList<HashMap<String, String>> customerDataList;
当我收到数据时,我创建一个新的 Hashmap 集合,如下所示:
HashMap<String, String> customer = new HashMap<>();
然后我只需添加我需要的值,例如
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...
然后,一旦我填充了该客户对象,我就把它添加到列表中:
customerDataList.add(customer);
现在,我想按一个值(我在上面设置的位置)对这些数据进行排序。
目前,在填充 customerDataList 后,我循环遍历它,构建所有位置的数组,对其进行排序,然后循环排序后的数组。在其中,我循环遍历 customerDataList 并将外部位置(排序值)与内部位置进行比较,并构建另一个已排序的 customerDataList。
有没有一种方法可以在不需要 3 个循环的情况下进行排序?
编辑:迈克,你的解决方案适用于 double 吗?
未排序的位置如下
1513.70
702.59
814.59
604.99
但是我给你的类(class)打电话后的最终名单是
1513.70
604.99
702.59
814.59
最佳答案
如果我正确理解了这个问题,听起来您可以首先使用自定义比较器对数组列表进行排序:
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());
当然,您可以使用匿名类来实现 Comparator<>
内联接口(interface)。
但顺便说一句,为什么要将客户实体存储在 HashMap 中?看起来很浪费..
关于java - 按一个字段对 ArrayList<Hashmap<String,String> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878672/