I'm writing a Java code that looks like this, and I have the feel it could be improved with some functional programming stuff :)
int rank = 1;
for (int i = 0; i < activities.size(); i++) {
if (i == 0) {
activities.get(i).setRank(rank);
else {
float currentAverage = activities.get(i).getQualityAverage();
float previousAverage = activities.get(i - 1).getQualityAverage();
activities.get(i).setRank(currentAverage == previousAverage ? rank : ++rank);
}
}
Assuming that activities List is sorted, the sense of this code is to assign a rank (a score) to every activity according with its place in the list. But there's a rule in the else case (when the itteration is equal or higher than second element) where I'm using the rank assigned to the previous element if both elements' qualityAverage property is exactly the same.
For instance:
| Activity | Quality Average | Rank |
|---|---|---|
| Read | 10 | 1 |
| Workout | 9.5 | 2 |
| Write | 9.2 | 3 |
| Study | 9.2 | 3 |
| Clean | 8 | 4 |
| Play guitar | 8 | 4 |
As I mentioned at the beginning, how could I write a Java BiFunction (maybe something similar to reduce()) in order to achieve a cleaner and smarter code.
You can create a static function in your Utility class or any other class, then use java stream to iterate the List. Here is an example: