1

My array contains items set out like:

"item_name_1::item_description::item_value"

(so each item in the array contains separate pieces of data which is later split at "::")

and my question is, how can i sort the array by the "ITEM_VALUE" (which is a numeric value), i have tried the following, with no luck:

Arrays.sort(inputArr, new Comparator<String>() {
    @Override
    public int compare(String entry1, String entry2) {
        String[] entry1Split = entry1.split("::");
        String[] entry2Split = entry2.split("::");

        return entry1Split[2].compareTo(entry2Split[2]);
    }
});
2
  • 1
    What is the problem with the code you've posted? It seems to be OK. Commented Sep 5, 2011 at 11:59
  • 1
    From perfromance perspective it worst splitting item each time you are doing comparision, split original array items in temporary arrays and then do sort Commented Sep 5, 2011 at 12:00

2 Answers 2

2

You should be able to do this:

Arrays.sort(inputArr, new Comparator<String>() {
    @Override
    public int compare(String entry1, String entry2) {
        String[] entry1Split = entry1.split("::");
        String[] entry2Split = entry2.split("::");

        return Double.valueOf(entry1Split[2]).compareTo(Double.valueOf(entry2Split[2]));
    }
});

that is, if your numerical values are floating point values. If they are integer, you can use Integer.valueOf instead of Double.valueOf.

Sign up to request clarification or add additional context in comments.

Comments

1

You may want to think about parsing the strings in the array and creating an object for each entry - something like

class Item {

    String value;
    String description
    Integer value;
}

that way you'll only parse the string once per object and not multiple times each time the sort algorithm needs to to do a compare.

3 Comments

While a useful comment in itself, it does not answer his question, therefore it should be a comment, not an answer.
There's no way to post multiline answers and sample codes in the comment.
The downside of a real time dynamic system - Aleks G answered the question whilst I was part way through typing my answer. There didn't seem to be any point in repeating the answer so I edited the repeated stuff and was left with what should arguably have been a comment.

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.