简体   繁体   中英

How to sort a array of tuple if the tuple is a pre-defined class without implement comparator in Java

I have a pre-defined tuple class which cannot be modified as follows:

public class Tuple {
    protected String name; 
    public Tuple(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

I have another class which defines an array of the above tuple:

public class Stack {
    protected ArrayList<Tuple> tupleLst; 
    public Stack(){
        this.tupleLst=new ArrayList<Tuple>(10);
    }
}

Then I need to sort the array of tuple in another class: for instance:

public class Algo {
    public static int Sort(Relation r){

    }
    public static void main(String[] arg){
    Algo.Sort();
}

The Relation r is the input array of tuples. I have searched online, where I saw many people actually are using Comparators and Collections.sort() to do that. However, after I tried, I noticed that the Tuple class need to implement comparators in order to sort. How can I sort the tuple without changing the first two classes? Thank you in advance!

Although Tuple cannot be modified, you can implement a Comparator of your own and then pass it to the Collections.sort() method (which will do a sort of your collection of tuples based on the comparator rule(s). For example:

Comparator<Tuple> myComparator = new Comparator<Tuple>() {
    public int compare(Tuple t1, Tuple t2) {
        //the comparison rules go here
    }
};
Collections.sort(tupleList, myComparator);

If you use Java8, you can achieve this in a single line:

myList.sort((t1, t2) -> { <comparison rules implementation> });

or (thanks to @MarkoTopolnik)

myList.sort(Comparator.comparing(t -> <<get sort key from t>>) 

I think you're confusing two methods. One way is to make your Tuple class implement the Comparable interface. I think this is the one you want to avoid since it seems you don't want to modify the Tuple class.

The other way is to define a new class, whose purpose is to compare two Tuples. This is what is called a Comparator. If you pass your list of Tuples and an instance of this comparator then you can sort your Tuples any way you like without modifying the Tuple class.

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