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

Java按价格排序JSON数组后展示未排序,该如何排查解决?

问题描述

我尝试实现JSON对象按价格从低到高排序,但是列表展示的时候始终是未排序的状态,不清楚哪里出了问题,希望能得到正确的解决方向。我查了不少资料都提到用Collection对JSON对象排序,我按照方法写了逻辑但没生效,下面是我的相关代码和数据。

原始JSON数据

[ {
 "symbol" : "SAN",
  "companyName" : "Banco Santander, S.A.",
  "marketCap" : 62296657920,
  "sector" : "Financial Services",
  "industry" : "Banks—Diversified",
  "beta" : 1.74298500000000000653699316899292171001434326171875,
  "price" : 3.5800000000000000710542735760100185871124267578125,
  "lastAnnualDividend" : 0.24899999999999999911182158029987476766109466552734375,
  "volume" : 4284228,
  "exchange" : "New York Stock Exchange",
  "exchangeShortName" : "NYSE",
  "country" : "ES",
  "isEtf" : false,
  "isActivelyTrading" : true
}, {
  "symbol" : "ABEV",
  "companyName" : "Ambev S.A.",
  "marketCap" : 48729493504,
  "sector" : "Consumer Defensive",
  "industry" : "Beverages—Brewers",
  "beta" : 0.93046200000000001129052407122799195349216461181640625,
  "price" : 3.0099999999999997868371792719699442386627197265625,
  "lastAnnualDividend" : 0.0970000000000000028865798640254070051014423370361328125,
  "volume" : 24947634,
  "exchange" : "New York Stock Exchange",
  "exchangeShortName" : "NYSE",
  "country" : "BR",
  "isEtf" : false,
  "isActivelyTrading" : true
}, {
  "symbol" : "LYG",
  "companyName" : "Lloyds Banking Group plc",
  "marketCap" : 41814462464,
  "sector" : "Financial Services",
  "industry" : "Banks—Regional",
  "beta" : 1.483138999999999985135445967898704111576080322265625,
  "price" : 2.310000000000000053290705182007513940334320068359375,
  "lastAnnualDividend" : 0.07022699999999999775912584709658403880894184112548828125,
  "volume" : 5825636,
  "exchange" : "New York Stock Exchange",
  "exchangeShortName" : "NYSE",
  "country" : "GB",
  "isEtf" : false,
  "isActivelyTrading" : true
}]

原有实现代码

public void downloadChangePercentage(String api) {

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
            Request.Method.GET,
            api,
            null,
            new Response.Listener<JSONArray>() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onResponse(JSONArray response) {
                    ArrayList<JSONObject> jsonStockList = new ArrayList<>();

                    for (int i = 0; i < response.length(); i++) {
                        try {
                            stockInfo = response.getJSONObject(i);
                            stockDetail = new StockDetails(stockInfo.getString("changesPercentage"), stockInfo.getString("symbol"), stockInfo.getString("price"), stockInfo.getString("name"));
                            stockListArrayList.add(stockDetail);
                            jsonStockList.add(response.getJSONObject(i));
                            searchStockAdapter.notifyDataSetChanged();

                            ArrayList<JSONObject> sortedStockList = sortJSONObject(jsonStockList);
                            for (int j = 0; j < sortedStockList.size(); j++) {
                                logText("sortedData", String.valueOf(sortedStockList.get(j)));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }},
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("error", error.toString());
                }
            });
    requestQueue.add(jsonArrayRequest);

}

ArrayList<JSONObject> sortJSONObject(ArrayList<JSONObject> jsonStockList){
    Collections.sort(jsonStockList, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject o1, JSONObject o2) {
            try {
                return Double.compare(o1.getDouble("price"), o2.getDouble("price"));
            } catch (JSONException e) {
                e.printStackTrace();
                return 0;
            }
        }
    });
    return jsonStockList;
}

问题解答

错误原因

  • 排序逻辑放错了位置:你把排序代码写在了遍历JSONArray的循环内部,每新增一个元素就排一次,不仅效率低,还不符合业务逻辑。
  • 没有更新界面绑定的数据源:你只对jsonStockList做了排序,但是列表Adapter绑定的渲染数据源是stockListArrayList,排序结果完全没有同步到这个列表,界面当然不会显示排序后的内容。
  • 列表刷新时机错误:你每次添加单个元素就调用一次notifyDataSetChanged,完全没有必要,排序完成后也没有再次触发列表刷新。

修正后的代码

public void downloadChangePercentage(String api) {
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
            Request.Method.GET,
            api,
            null,
            new Response.Listener<JSONArray>() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onResponse(JSONArray response) {
                    ArrayList<JSONObject> jsonStockList = new ArrayList<>();
                    // 先清空原有数据避免重复添加
                    stockListArrayList.clear();
                    
                    // 第一步:遍历所有数据先添加到列表
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject stockInfo = response.getJSONObject(i);
                            jsonStockList.add(stockInfo);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    // 第二步:对完整的JSON列表排序
                    Collections.sort(jsonStockList, new Comparator<JSONObject>() {
                        @Override
                        public int compare(JSONObject o1, JSONObject o2) {
                            try {
                                return Double.compare(o1.getDouble("price"), o2.getDouble("price"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                                return 0;
                            }
                        }
                    });
                    
                    // 第三步:把排序后的结果同步到Adapter绑定的数据源
                    for (int i = 0; i < jsonStockList.size(); i++) {
                        try {
                            JSONObject sortedItem = jsonStockList.get(i);
                            StockDetails stockDetail = new StockDetails(
                                    sortedItem.getString("changesPercentage"),
                                    sortedItem.getString("symbol"),
                                    sortedItem.getString("price"),
                                    sortedItem.getString("name")
                            );
                            stockListArrayList.add(stockDetail);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    // 最后统一刷新列表
                    searchStockAdapter.notifyDataSetChanged();
                    
                    // 打印排序后的结果验证
                    for (int j = 0; j < jsonStockList.size(); j++) {
                        logText("sortedData", String.valueOf(jsonStockList.get(j)));
                    }
                }},
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("error", error.toString());
                }
            });
    requestQueue.add(jsonArrayRequest);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:21:02