【问题标题】:Sorting an ArrayList<Hashmap<String,String> by one field按一个字段对 ArrayList<Hashmap<String,String> 进行排序
【发布时间】:2015-01-10 16:55:17
【问题描述】:

在一个 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 个循环的情况下进行排序?

编辑:Mike 你的解决方案是否适用于双打?

未排序的位置如下

1513.70
702.59
814.59
604.99

但是,我给你的班级打电话后的最终名单是

1513.70
604.99
702.59
814.59

【问题讨论】:

  • 我想这是因为我将它们存储为字符串?

标签: java android sorting arraylist


【解决方案1】:

如果我正确理解了这个问题,听起来您首先可以使用自定义比较器对数组列表进行排序:

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&lt;&gt; 接口。

但顺便说一句,为什么要将客户实体存储在哈希图中?好像很浪费。。

【讨论】:

  • 打败我。当存在更简洁的实现时,没有理由使用嵌套循环进行排序。
  • JavaDocs,这个方法需要两个double。
猜你喜欢
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 2019-02-03
  • 2017-06-01
  • 2017-02-24
相关资源
最近更新 更多