2

So, the array will be of the format:

String[][] resultsArray = new String[][] { 
        { X, Y, "2014-10-22 12:00", Z},
        { X, Y, "2014-10-24 12:00", Z},
        { X, Y, "2014-10-26 12:00", Z},
}; 

From this I need to retrieve the earliest date.

I already have a loop for another purpose that is looping through each item in the array, so I intend to reuse it. It is in the format:

for (int i=0; i < resultsArray.length; i++) {
    result += resultsArray[i][1] + "text" + resultArray[i][2];
}

My current thinking is to add the date value from the array into a new array (dateArray) on each iteration, then call Arrays.sort(dateArray) and grab dateArray[0].

However, this seems pretty inefficient and clumsy, and I suspect I'm missing some simple trick.

2
  • Can you use Java 8 and Streams?
    – user1907906
    Commented Oct 2, 2014 at 13:00
  • Potentially, I'd rather stick to backwards compatible methods where possible though.
    – Jake Lee
    Commented Oct 2, 2014 at 13:08

2 Answers 2

4

One (simple) solution is to assign a min value to the first element in the array, and then iterate from the second to the end comparing each value against the min (and because of your date format you can use lexical ordering). Something like,

String min = resultsArray[0][2];
for (int i=1; i < resultsArray.length; i++) {
    if (resultsArray[i][2].compareTo(min) < 0) {
        min = resultsArray[i][2];
    }
}
System.out.println(min);

Output is

2014-10-22 12:00
2
  • Very nice! I didn't think of writing a concise sort for it. Will mark as answer when available.
    – Jake Lee
    Commented Oct 2, 2014 at 13:09
  • Additionally, thanks for introducing me to the phrase "lexical ordering". Self explanatory, but sums up the concept nicely.
    – Jake Lee
    Commented Oct 2, 2014 at 13:56
2

Not as elegant as Elliott's, specially because resultsArray is altered by the sort method, but I think it's relevant to show here an alternative

    String[][] resultsArray = new String[][] { 
            { "X2", "Y2", "2014-10-24 12:00", "Z2"},
            { "X1", "Y1", "2014-10-22 12:00", "Z1"},
            { "X0", "Y1", "2014-10-26 12:00", "Z0"},
    }; 
    Arrays.sort(resultsArray, new Comparator<String[]>(){
        @Override
        public int compare(String[] o1, String[] o2) {
            return o1[2].compareTo(o2[2]);
        }
    });
    System.out.println(resultsArray[0][2]);

Not the answer you're looking for? Browse other questions tagged or ask your own question.