简体   繁体   中英

How to sort arraylist by mutiple level fields in Java

Class Activity{
    private int level;
    private Activity predecessor;
}

My program creates instances of Activity , puts them in an Arraylist and sorts them by two fields level and predecessor . predecessor is first compared.

For instance, if predecessor is not null , the predecessor Activity of the current activity should be first and it will be second. After satisfying the predecessor condition the following could be ordered by level .

List<Activity> activities = new ArrayList<Activity>();
//Add some activities.
activities.add(Activity);
activities.add(Activity);
Collections.sort(activities,getActivityComparator());

private Comparator<Activity> getActivityComparator() {
    return new Comparator<Activity>() { 
        public int compare(Activity act1, Activity act2) {                
            if (act1 == null) {
                if (act2 == null) {
                    return 0; // Both activities are null
                } else {
                    return -1; // act1 is NULL, so put act1 in the end of
                    // the sorted list
                }
            } else {
                if (act2 == null) {
                    return 1; 
                }
            }

         Activity preAct2 = act2.getPredecessor();
         if(preAct2!=null&&preAct2==act1)
             return -1;

          //Adding this by Joeri Hendrickx's suggestion
         Activity preAct1 = act1.getPredecessor();
         if(preAct1!=null&&preAct1==act2)
             return 1;

         return act2.getLevel()-act1.getLevel(); 
        }
    };
}

I have written the above code and tested a lot, but it outputted inconstant ordering if I putted different ordering into Arrarylist. so definitely this is incorrect method to implement this. Seems the root cause is not every two elements were compared. says Activity act1>Activity act2(by level condition), Activity act2>Activity act3(by level condition), it doesn't mean Activity act1>Activity act3(by predecessor condition).

Here I came up with an new idea that is to use bubble sort instead of using interface sort of Collections. it will compare every two elements that don't need comparator transitive any more. how do you think?

Can anyone help me?

The problem is that your comparator is not describing a correct symmetric and transitive relation.

Consider the following three objects:

act1{predecessor:null, level:1}    
act2{predecessor:act1, level:1}    
act3{predecessor:null, level:0}
act4{predecessor:act2, level:2}

Now, where comp is your comparator, comp(act1, act2) will return -1, but comp(act2, act1) will return 0. This is not symmetric .

comp(act1, act2) will return -1, comp(act2, act4) will return -1, but comp(act1, act4) will return 1. This is not transitive .

A comparator must describe a correct reflexive , symmetric and transitive relation in order for it to work.

Edited after seeing Axtaxt's post: the problem you describe here cannot be accomplished with a normal sort, because it's always possible to construct a scenario where, by these rules, you get a loop in your sort hierarchy. So it's not possible to make a transitive comparator with only this data .

As far as I understand, you cannot make your comparator transitive at all due to possibility of the following loop (thick line - predcessor, thin line - greater than):

在此处输入图片说明

So, you have a partial order and general purpose sorting algorithms are not applicable here.

If you need order by level only among successors of the same activity, you can achieve it using the following simple algorithm:

  • Build a multimap from Activity to its direct successors

  • Build a tree with the following properties:

    • Each node contains an activity, root node has null activity
    • Subnodes of each node correspond to direct successors of its activity, ordered by levels


    It can be created using the following algorithm:

    • Create a root node with null activity
    • For each node extract the corresponding successors from the multimap and create subnodes for them, apply it recursively

  • Traverse that tree

The compare method of comparator is defined as: "Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second."

Which means if you want act1 to be in the end when its null, you have to return a positive integer -> act1 is greater -> act1 will be at the end. You have your positive and negative integers mixed.

if (act1 == null) {
            if (act2 == null) {
                return 0; // Both activities are null
            } else {
                return 1; // act1 is NULL, so put act1 in the end of
                // the sorted list
            }
        } else {
            if (act2 == null) {
                return -1; 
            }
        }

Also, for the same reason you would need to use

return act1.getLevel()-act2.getLevel();

imaging a comparator for integers that receives 2 and 3. You would want it to return a negative int because the first argument is less than the second. -> arg1-arg2 = -1 instead of arg2-arg1 like you did...

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