Wednesday, August 31, 2016

An Easier Way of Comparing Multiple Fields

Suppose that we have a Squirrel class and assume that the species name will never be null. We could write a constructor to enforce that if we wanted to:

public class Squirrel {
private int weight;
private String species;

public Squirrel(String theSpecies) {
if (theSpecies == null)
throw new IllegalArgumentException();
species = theSpecies;
}

public int getWeight() {
return weight;
}

public void setWeight(int weight) {
this.weight = weight;
}

public String getSpecies() {
return species;
}
}

We want to write a Comparator to sort by species name. If two squirrels are of the species, we want to sort the one that weighs the least first.
With the introduction of static and default methods on interfaces within Java 8, there are now some new helper methods on Comparator. The code could be written as this:

import java.util.Comparator;

public class ChainingComparator implements Comparator<Squirrel> {
@Override
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);
}
}

No comments:

Post a Comment