1

i created a 2d string array (called data) which contains on the first position an integer (as a string) and on the second position a link to a file.

Examples:

["3", "Test3.pdf"]; ["1", "Test1.pdf"];  ["2", "Test2.pdf"];  ["10", "Test10.pdf"]

So now I need to sort the array ascending for the integer. So the result of the sorting should be an sorted array like:

["1", "Test1.pdf"];  ["2", "Test2.pdf"];["3", "Test3.pdf"];["10", "Test10.pdf"]

I found some sample code for this:

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(final String[] entry1, final String[] entry2) {
        final String time1 = entry1[0];
        final String time2 = entry2[0];
        return time1.compareTo(time2);
    }
});

but the problem is, that in this case it compares it with string logic, so the result would be-> 1,10,2,3. So I cannot archive the result with this. Do you know what can I do? You only can have an 2d array of one type? not mix of string and integer?

3
  • 1
    Do you need to have this as an array of arrays of strings? A simple collection of objects with separate int and String parts would almost certainly be better, not just here but throughout your code. Commented Nov 8, 2016 at 11:10
  • 1
    If you need to have strings in the array, just convert to int in the compare method. Commented Nov 8, 2016 at 11:11
  • The best structure to handle your problem is TreeMap<Integer,String> Commented Nov 8, 2016 at 11:25

2 Answers 2

1

The comparison can be done by converting the first element to Integer, as demonstrated in the following snippet:

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(final String[] entry1, final String[] entry2) {
        final Integer time1 = Integer.valueOf(entry1[0]);
        final Integer time2 = Integer.valueOf(entry2[0]);
        return time1.compareTo(time2);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can do like this

    Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(final String[] entry1, final String[] entry2) {
        final Integer time1 = Integer.parseInt(entry1[0]);
        final Integer time2 = Integer.parseInt(entry2[0]);
        return time1.compareTo(time2);
    }
});

2 Comments

Is this answer any different from the one posted 8 minutes earlier?
basically not..i just didn't see it while I was testing it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.