I am afraid you'll have to do a linear search:
public static WaterBody mostPowerful(WaterBody[] waterBodies) {
double maxValue = -1;
int indexOfMaxValue = -1;
for(int i = 0; i < waterBodies.length; i++) {
if(waterBodies[i].getElectricPower() > maxValue) {
indexOfMaxValue = i;
}
}
return waterBodies[indexOfMaxValue];
}
A more elegant solution can be achieved by using a Comparator
. It defines an Interface, which tells if one object is "bigger" or "smaller" than another. You can define a Comparator
like that:
Comparator<String> cmp = new Comparator<WaterBody>() {
@Override
public int compare(WaterBody o1, WaterBody o2) {
return Double.compare(o1.getElectricPower(), o2.getElectricPower());
}
};
If you'll need do operations like these often, it is advised to have a collection which always keeps it's content sorted, like a TreeSet
It would be a lot smarter to use a collection, which keeps it's content sorted.
TreeSet<WaterBody> waterBodiesTree = new TreeSet<>(cmp);
Collections.addAll(waterBodiesTree, waterBodies);
WaterBody smallest = waterBodiesTree.first();
WaterBody biggest = waterBodiesTree.last();
If you only need to sort your array, the first example I used turns into a one-liner (using the same Comparator
as defined earlier):
public static WaterBody mostPowerful(WaterBody[] waterBodies) {
return Collections.max(waterbodies, cmp);
}