I have a problem porting c++ code to Java. I have a list of pair as follows
vector<pair<pair<int,int>,int> > M;
I wrote the equivalent in Java as follows
List<Pair<Pair<Integer,Integer>,Integer>> pairList = new ArrayList<>();
Now in c++ code , M is filled with values and correspondingly I did the same in Java. Now down the line, c++ has a sort functionality as follows
sort(M.begin(), M.end());
Here is my problem, what is the equivalent comparator I need to write in Java? How do I use it ? I am assuming something of the following lines
Collections.sort(pairList, new MyComparator())
Could anyone help me understand what would be MyComparator ?
Pair class is as follows
class Pair<K,V>{
K k;
V v;
public void makePair(K k, V v){
this.k = k;
this.v = v;
}
}
Solution
I ended up implmenting MyComparator as follows
static class MyComparator implements Comparator<Pair<Pair<Integer,Integer>,Integer>>{
@Override
public int compare(Pair<Pair<Integer,Integer>,Integer> p1,Pair<Pair<Integer,Integer>,Integer> p2){
int a = p1.k.v.compareTo(p2.k.v);
if(a==0) return a;
else return p1.k.k.compareTo(p2.k.k);
}
}
Thank you all.