First of all, I am very new to Java 8, maybe my question won't apply to it at all...
So, I have a class that has a package private int and a String field. I have got to compare the instances by score and then by name. The solution is a class that must implement Comparator, and I'd like to solve it in Java 8, as I would code something like this, without the required class:
Arrays.sort(players, Comparator.comparing(Player.score).thenComparing(Player.name);
(players is an array of Player)
Is it possible at all? Overridden compare method should return an int, and I couldn't even get to a compiling code :(
I tried this first:
public class Sorter implements Comparator<Player> {
@Override
public int compare(Player o1, Player o2) {
return (int)(p1, p2) -> Comparator.comparing(Player.score).thenComparing(Player.name);
}
}
It fails at Player.score and Player.name, because "Non-static reference score cannot be referenced from a static context" I don't understand how would this be a static context.
Then I created getter methods for score and name temporarily (it must remain without getters), and the problem turned into "int is not a functional interface".
I'd really appreciate if someone can tell if it is possible at all, and if so, drive me to the correct solution.
Thank you very much!
Edit: my question is not a duplicate of the how to use static variables question, because I wanted to know if my task is OK to solve in Java 8 and if yes, how. Having a Comparator as a field in my class, seems to solve this question (if getters were reachable).