简体   繁体   中英

Collection.sort() second sorting based on first ordering

I have a list of questions in a List<RSSQuestion> , which I am trying to sort: first with their keyActivity , then in each keyActivity there are subActivities ; I need to sort out the questions based on the subActivities .

For example:

  1. OutLine Design (keyActivity)
    1. SubActivity One
  2. Specification (keyActivity)
    1. Overview
    2. Backlog

The code that I have is as follows, which is sorting the questions based on the keyActivity , but I don't know how can I do the second sorting based on the subActivity :

private static List<RSSQuestion> sortingExtractedData(List<RSSQuestion> extractedDataByKeyactivity) {
    List<RSSQuestion> exctractedData = new ArrayList<>();

    Collections.sort(extractedDataByKeyactivity, new Comparator<RSSQuestion>() {

        @Override
        public int compare(RSSQuestion o1, RSSQuestion o2) {
            return o1.getKeyActivity().compareTo(o2.getKeyActivity());
        }
    });

    for (RSSQuestion rssQuestion : extractedDataByKeyactivity) {
        Collections.sort(rssQuestion.getSubActivity(), new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
    }

    exctractedData.addAll(extractedDataByKeyactivity);
    return exctractedData;
}

Please let me know, how can I do the sorting for the rest subActivities ?

It should all be done with one Comparator , but you only go to the SubActivity when the KeyActivity is the same (ie keyActivityCompare == 0 ):

Collections.sort(extractedDataByKeyactivity, new Comparator<RSSQuestion>() {

    @Override
    public int compare(RSSQuestion o1, RSSQuestion o2) {
        int keyActivityCompare = o1.getKeyActivity().compareTo(o2.getKeyActivity());
        if (keyActivityCompare == 0)
          return o1.getSubActivity().compareTo(o2.getSubActivity());
        return keyActivityCompare;
    }
});

Collections.sort is stable :

the algorithm used by sort does not have to be a mergesort, but it does have to be stable.

That means that if two elements have the same value, the sorting does not change their order. You can make use of this by first sorting on sub activity and then on key activity.

As an example, I sort tuples of numbers, first on the first element, then on the second. Input:

(4, 2), (1, 0), (3, 3), (4, 1)

First sort on second element:

(1, 0), (4, 1), (4, 2), (3, 3)

Then sort again on first element:

(1, 0), (3, 3), (4, 1), (4, 2)

This way of sorting is reminiscent of radix sort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM