سؤال

I have a List<String> theList which has following kind of values

"2011-05-05|~JKED"
"2011-05-06|~ABC"
"2011-05-01|~XYZ"
"2011-05-01|~WWX"

As you could guess there are two "fields" in theList.

I want to sort theList on first field and then on second field such as I get following output after sorting operation

"2011-05-01|~WWX"
"2011-05-01|~XYZ"
"2011-05-05|~JKED"
"2011-05-06|~ABC"

If I take these two fields in a separate lists and do Collections.sort(field1List) Collections.sort(field2List) I get the desired output.

But, I want to know, how to use Collections.sort(theList, new Comparator(){}) to be able to sort above theList to get desired output. If it is not possible to solve through Comparator(), please suggest some method which might look like sortMultiFieldList(List<String> theList)

It is a long story why I have to have two or more fields in a single List.

Let me know if you need more clarification.

هل كانت مفيدة؟

المحلول

This is remarkably straightforward. You'll want to write a custom Comparator for this, and enforce its comparison logic to behave the way you want with respect to your two separate "fields".

The motivation here is that these fields are lexicographically compared to one another for the date portion, as well as the alphabetical string portion. If you find that the date comparison isn't giving you accurate results (and it may not; I'm not sure of any cases that it wouldn't work off hand, though), then convert it to a Date and compare that in-line.

Collections.sort(entries, new Comparator<String>() {
    @Override
    public int compare(String left, String right) {
        String[] leftFragments = left.split("[|]");
        String[] rightFragments = right.split("[|]");
        if(leftFragments[0].compareTo(rightFragments[0]) == 0) {
            return leftFragments[1].compareTo(rightFragments[1]);
        } else {
            return leftFragments[0].compareTo(rightFragments[0]);
        }
    }
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top