【问题标题】:Sort List<String[]> by order of Dates in Java在 Java 中按日期顺序对 List<String[]> 进行排序
【发布时间】:2017-09-07 06:31:06
【问题描述】:

我有一个形式为字符串数组的列表

List<String[]> currentLoadAddressLocations = new ArrayList<>();

通过 JSONObject 数组设置和解析

try {
            JSONObject dataObject = new JSONObject(data);
            JSONArray dataObjArray = dataObject.getJSONArray("stops");
            Log.i(TAG, dataObjArray.toString());

        for (int i = 0; i < dataObjArray.length(); i++) {
            JSONObject addressAndLocation = dataObjArray.getJSONObject(i);
            addressGPointJSON.add(addressAndLocation.getString("address"));
            locationGPointJSON.add(addressAndLocation.getString("location"));
            cityGPointJSON.add(addressAndLocation.getString("city"));
            stateGPointJSON.add(addressAndLocation.getString("state"));
            fromGPointJSON.add(addressAndLocation.getString("from"));
            latGPointJSON.add(reverseGeocoderLatLong(addressGPointJSON.get(i) + ", " + cityGPointJSON.get(i) + ", " + stateGPointJSON.get(0), true));
            longGPointJSON.add(reverseGeocoderLatLong(addressGPointJSON.get(i) + ", " + cityGPointJSON.get(i) + ", " + stateGPointJSON.get(0), false));

            currentLoadAddressLocations.add(i,
                    new String[]{
                            fromGPointJSON.get(i),
                            addressGPointJSON.get(i),
                            locationGPointJSON.get(i),
                            cityGPointJSON.get(i),
                            stateGPointJSON.get(i),
                            latGPointJSON.get(i),
                            longGPointJSON.get(i)
                    });
        } // end of for loop
        } // end of try catch block
        catch(JSONException e){
            e.printStackTrace();
        }

目前,代码返回了我需要的数据结构,一个 String[] 形式

["2017-03-30 21:00:00", "Address example 123", "Location Example", "CITY", "STATE", "lat", "long"]

根据返回的 JSON 对象中的停靠点数重复。我需要找到一种方法来按时间在 currentLoadAddressLocations 数组中从上到下对数组的第一个值进行排序,所以如果其中一个日期是“2017-03-30 15:00:00”,另一个是“2017” -03-30 14:00:00" 然后前面的那个优先并将日期移动到 currenLoadAddressLocations 数组的顶部,同时将第二个放在下面。我很难找到这样做的方法。目前我知道如果我将日期解析为可以比较日期:

Date from = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse("2017-03-30 21:00:00");

但不知道如何在循环通过 currentLoadAddressLocations 列表时解决此问题。此外,我不知道如何访问这些值以比较它们。我可以通过使用循环选择

for(String[] array: currentLoadAddressLocations){
            for(String s: array){
                Log.i(TAG,"ITEM: " +  s);
            }
        }

但由于它们位于字符串数组中,除非我更改它们然后将它们解析回字符串,否则它们无法更改为日期格式。

任何建议将不胜感激。

【问题讨论】:

    标签: java android list sorting arraylist


    【解决方案1】:

    答案是您应该将 String[] 转换为 AddressDateLocation 类数组。一旦你这样做了,按照你想要的方式对数据进行排序会容易得多

    public class AddressDateLocation implements Comparable<AddressDateLocation> {
      Date date;
      String address;
      String location;
    
      public void setDate(Date d) {}
      public Date getDate() ...
      public void setLocation(String loc) ...
      public String getLocation() ...
      public void setAddress(String addr) ...
      public String getDate() ...
    
      public int compareTo(AddressDateLocation other) ...
    }
    

    【讨论】:

    • 我正在考虑类似的事情,但无法弄清楚如何正确引入 compareTo 方法覆盖以及如何使用它,这似乎是最合理的想法。你能给我一个关于如何设置 compareTo 方法的建议吗?我非常感谢您的回答哦,伟大的后院吊桥建造者!
    • 只是做一些研究。 Comparable 接口被解释了无数次。如何做到这一点的例子不胜枚举。
    • 知道了,实际花费的时间比我想象的要少。干杯!
    【解决方案2】:

    您需要的数据结构可能不是字符串数组,除非这些片段的顺序最终在公共 API 中。您最好将信息保存在具有Map 语义的原生JSONObject 中。然后你可以简单地按时间戳排序:

    List<JSONObject> currentLoadAddressLocations = TODO(/* implement this */);
    currentLoadAddressLocations.sort((o1, o2) -> { 
        return o1.getString("date").compareTo(o2.getString("date"))
    });
    

    注意:问题中建议的日期格式可以使用它们的文本表示来比较时间戳。

    【讨论】:

      【解决方案3】:

      您可以将日期转换为 LocalDateTime 对象并使用 compareTo 方法。

      【讨论】:

        【解决方案4】:

        我会像这样使用List#sort 函数:

        currentLoadAddressLocations.sort((sa1, sa2) -> { // sa = String Array
            try {
                String pattern = "yyyy-MM-dd HH:mm:ss";
                return new SimpleDateFormat(pattern, Locale.US).parse(sa1[0])
                        .compareTo(new SimpleDateFormat(pattern, Locale.US).parse(sa2[0]));
            } catch (ParseException e) {
                // If your dates are all valid you shouldn't come here.
                e.printStackTrace();
                return -1; // move all parse ParseExceptions to the first positions
            }
        });
        

        【讨论】:

        • 这是金子。谢谢 Johan,我没有在比较选项的过程中,看看哪个答案最适合我,你的例子完美无缺,尽管我不得不做一些小的改动,因为我的 Android 项目此时不支持 lambda。它仍然可以完美运行!
        • 请记住,异常并没有真正得到处理。仅打印堆栈跟踪并将故障移动到列表的第一个位置。如果您 100% 确定字符串是可解析的,那么它不应该是一个真正的问题。否则你必须找到正确处理异常的方法。
        • 我想了很多,它直接来自我们有问题的 API,所以我非常肯定它会在可预见的未来保持这种状态。谢谢你的提醒!你就是炸弹!
        猜你喜欢
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 2010-12-22
        • 2019-02-03
        • 1970-01-01
        • 2012-02-18
        相关资源
        最近更新 更多