I'm prepping up for the Java 8 certificate and the following has me puzzled a littlebit, maybe someone can help me with this? In the example, a Squirrel class is modelled. It has a name and a weight. Now you can make a Comparator class to sort this thing using both fields. So first sort by name and then by weight. Something like this:
public class ChainingComparator implements Comparator<Squirrel> {
public int compare(Squirrel s1, Squirrel s2) {
Comparator<Squirrel> c = Comparator.comparing(s -> s.getSpecies());
c = c.thenComparingInt(s -> s.getWeight());
return c.compare(s1, s2);
}
}
So far so good.. but then the puzzling part. Underneath the code example, they state that you can write this in one single line by using method chaining. Maybe I misunderstand, but when I chain the comparing and the thenComparing parts, I get a compile error. It's got to do with the types of objects that are compared (first String, then int).
Why does it work when I put in an intermediate variable and not when chaining? And is it possible to chain at all?