You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Fragment与Adapter中使用Collections.sort()实现距离由近到远排序

问题原因

你当前代码存在两个核心问题导致排序不符合预期:

  • 排序规则错误:你自定义的Comparator是按露营点名称排序,并没有用到你计算好的距离字段
  • 排序时机错误:你把Collections.sort放在了遍历的for循环内部,每添加一个元素就执行一次全量排序,不仅性能浪费,也没有必要

修正方案

把排序逻辑移到for循环结束后,同时修改比较器规则为按距离升序(近的在前)即可,修正后代码如下:

if(seatch_bar.getText().toString().equals("")){
    camperSiteModel.clear();
    for(DataSnapshot snapshot : dataSnapshot.getChildren()){
        CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);

        double radLat1 = rad(camperSiteModel1.getCamperSiteLatitude());
        double radLat2 = rad(latitude);
        double a = radLat1 - radLat2;
        double b = rad(camperSiteModel1.getCamperSiteLongitude()) - rad(longitude);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;  
        Log.i("Distance",Math.ceil(s)+"");

        camperSiteModel1.setDistance(Math.ceil(s));
        camperSiteModel.add(camperSiteModel1);
    }
    // 所有元素添加完成后统一排序,按距离升序(近的排在前面)
    Collections.sort(camperSiteModel,new Comparator<CamperSiteModel>() {
        @Override
        public int compare(CamperSiteModel o1, CamperSiteModel o2) {
            // 用Double.compare避免浮点数精度问题导致的排序异常
            return Double.compare(o1.getDistance(), o2.getDistance());
        }
    });
    camperSiteAdapter.notifyDataSetChanged();
}

补充说明

如果需要按距离由远到近排序,只需要把比较器的返回值改成Double.compare(o2.getDistance(), o1.getDistance())即可。


内容的提问来源于stack exchange,提问作者user16489264

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:57:01