sigillum_conf
sigillum_conf

Reputation: 433

Sort List<String[]> by order of Dates in Java

I have a List of String arrays of the form

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

That gets set and parsed through a JSONObject Array

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();
        }

Currently, the code gives me back the data structure that I need, a String[] of the form

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

repeated depending on how many stops where in the JSON object that was returned. I need to find a way to sort the first value of the array from top to bottom inside the currentLoadAddressLocations array by time, so if one of the dates is "2017-03-30 15:00:00" and the other is "2017-03-30 14:00:00" then the one that is before takes precedence and moves the date to the top of the currenLoadAddressLocations array while at the same time araging the second one to be below. I am having a hard time trying to find a method of doing so. Currently I know that I can compare dates if I parse the dates as:

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

But do not know how to work around this issue while looping through the currentLoadAddressLocations List. Further more, I do not know how to access the values in order to compare them. I can loop through the selection by using

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

But since they are inside a String array they cannot be changed into a date format unless I change them and then parse them back to strings.

Any suggestions will be greatly appreciated.

Upvotes: 0

Views: 430

Answers (4)

3limin4t0r
3limin4t0r

Reputation: 21130

I would use the List#sort function like so:

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
    }
});

Upvotes: 1

Barn on a Hill
Barn on a Hill

Reputation: 387

You could make the dates into LocalDateTime objects and use the compareTo method.

Upvotes: 1

Raffaele
Raffaele

Reputation: 20885

The data structure you need is likely not an array of String's, unless the order of the pieces ends up in a public API. You'd better keep the information in the native JSONObject, that has Map semantics. Then you can simply order by timestamp with:

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

Note: the date format suggested in the question makes it possible to compare timestamps using their textual representation.

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

The answer is you should convert your String[] into a AddressDateLocation class array. Once you do that, it will be much easier to sort you data the way you want

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) ...
}

Upvotes: 2

Related Questions