I am studying Spak, recently saw a lot of online for Spark with Java to achieve two ordering method, for the custom key approach is basically to implement the Ordered<> interface, rewrite $greater, $greater $eq, $less, $ Less$eq, Compare, CompareTo methods, defining hashcode, equals
Feel good trouble, in fact we custom key just use the inside of the CompareTo method, other $greater, $greater $eq, $less, $less $eq, compare do not make any changes, hashcode, Equals method is not needed, do not know why everyone likes to write so complex, and in fact, we do not have to implement ordered<> interface, as long as the implementation of Comparable<t> interface rewrite CompareTo method on the line, very concise, Below is my custom key:
Import java.io.Serializable;
Import scala.math.Ordered;
/**
* Custom two-time sort key
*/
public class Secondarysortkey implements Comparable<secondarysortkey>,serializable {
Private static final long serialversionuid = -2366006422945129991l;
private int first;
private int second;
Public Secondarysortkey (int first, int second) {
This.first = First;
This.second = second;
}
@Override
public int CompareTo (Secondarysortkey other) {
if (This.first-other.getfirst ()! = 0) {
return This.first-other.getfirst ();
} else {
return This.second-other.getsecond ();
}
}
public int GetFirst () {
return first;
}
public void Setfirst (int first) {
This.first = First;
}
public int Getsecond () {
return second;
}
public void Setsecond (int second) {
This.second = second;
}
}
Tested without problems. I don't know if I understand enough. Or we deliberately put Java custom key method to write complex points to reflect the simplicity and elegance of Scala (hahaha), if there is no place to take into account please advise!!!
This article is from the "Small Ling World" blog, please be sure to keep this source http://beyond520.blog.51cto.com/10540356/1920267
Spark two-order custom key in Java